为什么可变大小的数组可以工作而不是动态数组?

Why does array with variable-sized work but not dynamic array?

首先,我是编程新手,不知道“可变大小数组”和“动态数组”是什么意思。 我只是用这些词来描述我的情况。随意使用正确的命名法进行编辑。 现在的问题,我有以下代码:-

...
int n;
printf("Enter number of rows/columns = ");
scanf(" %d",n);
int a[n][n];
...

...
int n;
n=6;
int a[n][n];
...
n=7;
...
n=4;
...

都编译成功

为什么?

scanf()

中使用&

当您使用 scanf from <stdio.h>, you need to pass a pointer to it. You can read more about why that's the case here: Use of & in scanf() but not in printf()

扫描用户输入时
int n;
printf("Integer: ");
scanf("%d", &n);
int a[n][n];

变长数组

评论中提到variable-length array is just an array whose length is determined at run time instead of at compile time. In your case the length is determined by the variable n which makes it a variable-length array. And as Eugene Sh.,改变变量n并不会在定义后修改数组的长度。

在这两个代码片段中都使用了可变长度数组,因为在它们的声明中没有使用整数常量表达式来指定数组中元素的数量。

没有动态分配的数组。

第一个代码片段在调用 scanf 的语句中存在错误。

scanf(" %d",n);

参数应为指向变量的指针n

scanf(" %d", &n);

也就是通过函数scanf改变变量n你必须通过引用将它传递给函数

在 C 中,按引用传递意味着通过指向对象的指针间接传递对象。因此取消引用指针函数将直接访问必须修改的对象。

注意第二个代码片段在数组声明后改变变量n的值不会改变数组a.

中元素的数量
int n;
n=6;
int a[n][n];
...
n=7;
...
n=4;

根据数组声明前存储在变量n中的值,数组a将恰好有6个元素。

这是一个演示程序。

#include <stdio.h>

int main(void) 
{
    size_t n;
    
    do
    {
        printf( "Enter number of rows/columns (greater than 0 ) = " );
        
    } while ( !( scanf( "%zu", &n ) == 1 && n != 0 ) );
    
    int a[n][n];
    
    printf( "The size of the array declared like int a[%zu][%zu] is %zu.\n", 
            n, n, sizeof( a ) );
    
    return 0;
}

程序输出可能看起来像

Enter number of rows/columns (greater than 0 ) = 10
The size of the array declared like int a[10][10] is 400.

可变长度数组应具有自动存储持续时间(也就是说,它不能在文件范围内声明,或者具有存储说明符 static;它可以在块范围内声明)。

来自 C 标准(6.7.6.2 数组声明符)

4 If the size is not present, the array type is an incomplete type. If the size is * instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations or type names with function prototype scope; such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type. (Variable length arrays are a conditional feature that implementations need not support; see 6.10.8.3.)