我对最后一个printf语句有疑问,为什么我们不能使用int arr来打印正在显示一些垃圾值的数组。

int main() {
    int intArr[],*p,i,n;
    scanf("%d",&n);
    p=intArr;
    p=(int *)malloc(n*sizeof(int));
    for(i=0;i<n;i++)
    {
        scanf("%d",p+i);
    }
    for(i=0;i<n;i++)
    {
        printf("%d",intArr[i]);

    }
    return 0;
}

最佳答案

也许您的目的是使用可变大小的数组,在读取n后对其进行初始化:

// read 'n'
int n;
scanf("%d",&n);

// create an automatic (temporary) array of size 'n'
// which will be deallocated once it leaves scope
int intArr[n];

// this part is just making it harder for compiler to
// do static analysis - why not simply use `intArr`?
int * p = intArr;


但是,由于使用的是malloc,因此根本不需要临时数组,而可以使用它:

// read 'n'
int n;
scanf("%d",&n);

// allocate an array of size 'n'
int * p = malloc(n * sizeof *p);

...

// release the memory
free(p);

关于c - 对指针和数组感到困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55497526/

10-11 21:04