Aldo Aldo - 1 month ago 14
C Question

Dynamic array using malloc and realloc?

I'm trying to collect input integers one by one. My array starts with size 1 and I want to expand it by 1, with every input collected (is this a smart thing to do?)

Anyway, this is the code I managed to come up with, but it's not working as intended.

After this process, sizeof(array) always returns 8, which I assume means that the array is only being resized once. (sizeof(int) is 4 bits)

Trying to output the array results in multiple instances of the first input variable.

OUTPUT CODE

for(int s=0;s<sizeof(array)/sizeof(int);s++){
printf("%i\n",array[i]);
}


ORIGINAL CODE:

int i;
int size = 1;
int *array = malloc(size * sizeof(int));
int position = 0;

do{
i = getchar() - 48;
f (i != -16 && i != -38 && i != 0) {
array[position] = i;

position++;
size++;
*array = realloc(array, size * sizeof(int));
}
} while (i != 0);


UPDATED STILL NOT WORKING CODE

int i;
int size = 1;
int *array = malloc(size * sizeof(int));
int position = 0;

do{
i = getchar() - 48;
f (i != -16 && i != -38 && i != 0) {
array[position] = i;

position++;
size++;
array = realloc(array, size * sizeof(int));
}
} while (i != 0);

Answer

(With some copy-paste from my comment:) sizeof(array) returns 8 because it equals sizeof(int*) which is 8 (you're probably compiling as 64-bit). sizeof doesn't work how you think for pointers to arrays.

Similarly, your output code is wrong, for the same reason. You only print the first two elements because sizeof(array)/sizeof(int) will always be 8/4=2. It should be

for(int s=0;s<size;s++){
    printf("%i\n",array[s]);
}

(note also changed index variable i to s) where size is the variable from your other code chunk(s). You cannot find the length of the array from sizeof if it's dynamically allocated with pointers; that's impossible. Your code must "remember" the size of your array.