gpt4 book ai didi

c++ - 并非此数组中的所有值都设置为0吗?

转载 作者:行者123 更新时间:2023-12-01 14:43:29 25 4
gpt4 key购买 nike

我实质上是在尝试创建一个数组并让用户输入一个方矩阵。由于某些原因,并非所有值都设置为0,我不确定为什么。这是代码:

#include <iostream>

using namespace std;

int main()
{
int row, col, n;
cout<<"Enter a positive odd integer above 1: ";
cin>>n;
int mgcsqre[n][n] = {0};
}

最佳答案

首先,您应该知道可变长度的数组只是GCC扩展,而不是C或C++标准的一部分。您可以看一下GCC docs:

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.



因此,以下代码:

#include <iostream>

int main() {
int n = 5;

int mgcsqre[n][n] = { 0 };

for (int i = 0; i < n; i++) {
std::cout << std::endl;
for (int j = 0; j < n; j++) {
std::cout << mgcsqre[i][j] << " ";
}
}
}

可以使用GCC完美编译,但是使用CLANG编译时会产生以下错误:

error: variable-sized object may not be initialized



现在,以上使用GCC编译的代码将产生以下结果:
0 32536 -1273401536 32536 -1270477024 
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

为什么输出一些垃圾值?因为行为是C++标准本身未定义的。

如果尝试在C中编译等效代码:

#include <stdio.h>

int main() {
int n = 5;

int mgcsqre[n][n] = { 0 };

for (int i = 0; i < n; i++) {
printf("\n");
for (int j = 0; j < n; j++) {
printf("%d ", mgcsqre[i][j]);
}
}

return 0;
}

您将收到以下错误:

error: variable-sized object may not be initialized



因为:

C99 §6.7.8 [Initialization]

The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.



那么,什么是初始化可变长度数组的正确方法呢?有两种选择:
  • 使用 memset
  • 使用传统的for循环遍历所有元素并将其初始化为0
  • 关于c++ - 并非此数组中的所有值都设置为0吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60133160/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com