Problem in code in C executing a function

2

Hello, I have a problem with this code. I'm implementing the bubble sort function. But something curious happens when running this code. The variable n that indicates the amount of vector space in the main function is modified after executing the bubbleSort () function. And I'm not understanding the reason for this change since it does not pass the pointer from variable n to the sort function. Could someone please explain the reason to me?

The n always modifies to the highest value of the vector.

#include <stdio.h>
#include <stdlib.h>

int ASC(int x, int y) {
    return x < y;
}

int DSC(int x, int y) {
    return x > y;
}

void bubbleSort(int *list, int start, int size, int cmp(int, int)) {
    int cont, hold;
    for(; start < size-1; start++) {
        for(cont = 0; cont < size-start; cont++) {
            if(cmp(list[cont+1], list[cont])) {
                hold = list[cont];
                list[cont] = list[cont+1];
                list[cont+1] = hold;
            }
            printf("hold = %d\n", hold);
            printf("cont = %d\n\n", cont);
        }
    }
}

int main() {
    int vetor[] = {1,8,7,14,5};
    int n = sizeof(vetor)/sizeof(int);
    printf("n = %d\n", n);
    bubbleSort(vetor, 0, n, ASC);

    printf("n = %d\n", n);
    int i;
    for(i = 0; i < n; i++) {
        printf("%d ", vetor[i]);
    }
    return 0;
}
    
asked by anonymous 27.08.2016 / 03:17

1 answer

1

gmorikawa this question really was difficult to understand, but there it goes:

The concept of pointers is the same as the concept of arrays in c, when data is stored in the stack they are sequences in memory.

Imagine the following situation: You have declared an array with 5 indexes and then after an integer (outside the array, but still in the stack sequence) both in the stack:

int vetor[] = {1,8,7,14,5};
int n = sizeof(vetor)/sizeof(int);

So the operating system organized its data as follows (fictitious, but for educational purpose)

Índice       | Valor | End. Memória
int vetor[0] |   1   | 0x000
int vetor[1] |   8   | 0x001
int vetor[2] |   7   | 0x002
int vetor[3] |  14   | 0x003
int vetor[4] |   5   | 0x004
int n        |   ?   | 0x005

In your BubbleSort function, you access during the iteration the current index (iterator) and the index + 1.

When arriving at the last element of the array the next element accessed corresponds in type (int), but is no longer part of the array; This element is accessed sequentially in memory because it is a valid pointer to an integer (points to the variable "n").

The value is tested and follows the same sort process ...

If the value of vector ["last_indice" + 1] is changed, the variable "n" will receive the value assigned to it.

C is very good, gives you many possibilities. But sometimes these possibilities generate a very different error than expected (in the index case out of range for the array).

I hope I have been able to help.

    
27.08.2016 / 06:36