I'm trying to learn pointer in C and am writing this little integer array pointer exercise,but ran into a invalid application of sizeof to incomplete type int[] problem. Please tell me where did I go wrong and how to solve it. Thank you.
#include <stdio.h>
int intA[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int intB[];
void int_copy(const int *source, int *destionation, int nbr)
{
int i;
for(i=0;i<nbr;i++)
{
*destionation++ = *source++;
}
}
int main()
{
int *ptrA = intA;
int *ptrB = intB;
int sizeA = sizeof(intA);
int nbrA = sizeof(intA)/sizeof(int);
printf("\n\n");
printf("[Debug]The size of intA is:%d\n", sizeA);
printf("[Debug]That means the number of elements is:%d\n", nbrA);
printf("\n\nThe values of intA are:\n");
int i;
for(i=0;i<nbrA;i++)
{
printf("[%d]->%d\n", i, intA[i]);
}
int_copy(ptrA, ptrB, nbrA);
int sizeB = sizeof(intB);
int nbrB = sizeof(intB)/sizeof(int);
printf("\n\n");
printf("[Debug]The size of intB is:%d\n", sizeB);
printf("[Debug]That means the number of elements is:%d\n", nbrB);
printf("\n\nThe values of intB are:\n");
for(i=0;i<nbrB;i++)
{
printf("[%d]->%d\n", i, *ptrB++);
}
}
# cc -g -o int_copy int_copy.c
int_copy.c: In function 'main':
int_copy.c:36: error: invalid application of 'sizeof' to incomplete type 'int[]'
int_copy.c:37: error: invalid application of 'sizeof' to incomplete type 'int[]'
The strange thing that I observed is when I ran gdb, I monitored that the copy function, int_copy, runs for 9 times which seems to be right, but the print of intB after the copy function only displays one item in that array.
I'm still struggling about pointers now, so please do help me and forgive my ignorance. Thank you very much.
intB is basically a pointer, and sizeof on it will yield the same as sizeof on int, that's why the print appears only once.
intA is an array with a known size, so the sizeof works.
You need to remember that sizeof is not a run-time call, although it may look so syntactically. It's a built-in operator that returns the size of the type in bytes at the compilation time, and at the compilation time intB is a pointer that should later point to a newly allocated array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With