'sizeof'无效应用于不完整类型'int []'当访问指针指向的整数数组时

bes*_*twc 1 c pointers

我正在尝试学习C中的指针并且正在编写这个小整数数组指针练习,但遇到了一个无效的sizeof类型int[]问题的应用程序.请告诉我哪里出错了以及如何解决.谢谢.

#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[]'
Run Code Online (Sandbox Code Playgroud)

我观察到的奇怪的事情是当我运行gdb时,我监视到复制函数int_copy运行了9次似乎是正确的,但是复制函数之后的intB的打印只显示该数组中的一个项目.

我现在仍在努力争取指针,所以请帮助我并原谅我的无知.非常感谢你.

lit*_*adv 10

intB基本上是一个指针,sizeof它会产生相同sizeofint,这就是为什么打印只出现一次. intA是一个已知大小的数组,所以sizeof工作.

你需要记住,这sizeof不是一个运行时调用,虽然它看起来可能是语法上的.它是一个内置的运算符,它在编译时以字节为单位返回类型的大小,并且在编译时intB是一个指针,该指针稍后应指向新分配的数组.

  • @bestwc:`sizeof`是在编译时计算的. (2认同)