Possible Duplicate:
How to get the size of dynamically allocated 2d array
I can’t find what I did wrong here. I want to create an array which its size is based on user input, get the data (integers) for the array from user input, and print the array integers.
The problem is that it only prints the first array element, i.e intArr[0].
int main()
{
int i, n, *intArr;
printf("Type the array size:\t");
scanf("%d", &n);
intArr = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; ++i)
{
printf("Type a number\t");
scanf("%d", intArr + i);
}
printArr(intArr);
}
void printArr(int *arr)
{
int i;
for (i = 0; i < (sizeof(arr) / sizeof(*arr)); ++i)
printf("%d ", *(arr + i));
}
The type of
arris anint*sosizeof(arr)will be thesizeof(int*)and not the number of elements inarr. On your systemsizeof(int*)and thesizeof(int)is the same, giving 1 as the result so the loop prints one element only.Pass the number of elements as an argument to the
printArr()function.Note:
free()what you havemalloc()d.malloc()is unnecessary.scanf()to ensure successful.