Reputation: 81
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.
Upvotes: 3
Views: 22766
Reputation: 6878
Actually your int intB[];
statement is invalid, which compiler are you using?
Also, beware that arrays and pointers are not really the same. You can however use the array handle in a call to a function that expects a pointer, so you can give intA
to your int_copy
function without copying it to a pointer. http://www.lysator.liu.se/c/c-faq/c-2.html
Upvotes: 1
Reputation: 92271
You are also in trouble here, because IntB doesn't have a size so int_copy really doesn't work for it. There is nowhere to copy the ints!
When declaring an array, you have to either give the size inside [] or use an initializer with the values, so the compiler can count them and figure out the size itself.
Upvotes: 2
Reputation: 20272
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.
Upvotes: 12