I wanted to expand an array dynamically as the user enters the values using below code.
#include<stdio.h>
#include<stdlib.h>
int main(){
int *number=(int *)malloc(sizeof(int)),i=0,*new_ptr;
printf("Enter a number to store it or -1 to finish the storage\n");
scanf("%d",number);
while(*(number+i)!=-1){
printf("Enter a number to store it or -1 to finish the storage:\n");
number=(int *)realloc(number,sizeof(number)+sizeof(int));
i++;
scanf("%d",number+i);
};
for(int j=0;j<i;j++){
printf("%d ",number[j]);
};
return 0;
}
it gives this output
Enter a number to store it or -1 to finish the storage
1
Enter a number to store it or -1 to finish the storage:
2
Enter a number to store it or -1 to finish the storage:
3
Enter a number to store it or -1 to finish the storage:
4
Enter a number to store it or -1 to finish the storage:
5
Enter a number to store it or -1 to finish the storage:
6
Enter a number to store it or -1 to finish the storage:
7
Enter a number to store it or -1 to finish the storage:
8
Enter a number to store it or -1 to finish the storage:
9
Enter a number to store it or -1 to finish the storage:
0
Enter a number to store it or -1 to finish the storage:
-1
1 2 3 4 5 6 7 8 540155953 540287027
the junk file values happens only when the number of user input is greater than 8. Why it happens and how to fix it?
sizeof(number)is not what you think it is.sizeof(number)is the size of the pointer pointing to the allocated memory.inumbers, how manyintelements do you need to store them? If oneintelement takessizeof (int)bytes, how many bytes do you need to storeielements of typeint? What argument should you pass toreallocto request that many bytes?i++;beforenumber = realloc(number, sizeof *number * (i + 1));NULLelse assign that tonumber.scanfwhich discards the return value is always a bug. You must always check the value returned, whether it is simplyif( scanf(...)orwhile( scanf(...)you must not discard the return value.