Invalid application 'sizeof' for incomplete type 'int []' When accessing the integer array pointed by a pointer

I am trying to learn a pointer in C, and I am writing this exercise with a small integer, but have encountered an invalid sizeof application on an incomplete type problem int[] . Please tell me where I made a mistake and how to solve it. Thanks.

 #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 when I ran gdb was that I controlled the copy function int_copy to work 9 times, which seems correct, but printing the intB after the copy function displays only one element in this array.

I am still fighting for pointers, so please help me and forgive my ignorance. Thank you very much.

+1
source share
3 answers

intB is basically a pointer, and sizeof on it will have the same value as sizeof on int , so printing appears only once. intA is an array with a known size, so sizeof works.

You should remember that sizeof not a call at runtime, although it may look like this syntactically. This is a built-in operator that returns the size of the type in bytes at compile time, and at compile time, intB is a pointer that should later point to a newly allocated array.

+10
source

You also have problems because IntB has no size, so int_copy really doesn't work for it. Nowhere to copy ints!

When declaring an array, you need to either specify the size inside [], or use an initializer with values ​​so that the compiler can calculate them and find out the size itself.

+2
source

Actually your statement is int intB[]; which compiler are you using?

Also, be careful that arrays and pointers are actually not the same. However, you can use an array descriptor in a function call that expects a pointer, so you can pass intA your int_copy function without copying it to the pointer. http://www.lysator.liu.se/c/c-faq/c-2.html

+1
source

Source: https://habr.com/ru/post/1439543/


All Articles