为什么第一行会出现零以外的其他值?

Why some other value than zero is coming in first row?

本文关键字:其他 一行 为什么      更新时间:2023-10-16

我正在尝试使用C++中的数组制作一个MxN零矩阵。但有些值不是零。请帮我解决这个问题。

#include <iostream>
using namespace std;
int main()
{
int m,n;
cin>>m>>n;
int i,j,s[m][n]={0};
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout<<s[i][j]<<" ";
}
cout<<endl;
}
}

输入:4 4

输出:

0 11097 1757549776 11097 
0 0 0 0 
0 0 0 0 
0 0 0 0 

预期输出:

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

此代码在标准C++中无效,因为它不允许在没有此类new的情况下创建动态数组。

例如,下面是 VC++ 输出:https://rextester.com/VFVL26633

ource_file.cpp(9): note: failure was caused by non-constant arguments or reference to a non-constant symbol
source_file.cpp(9): note: see usage of 'm'
source_file.cpp(14): warning C4552: '<<': operator has no effect; expected operator with side-effect
source_file.cpp(18): error C2036: 'int [m][n]': unknown size

如果你做nm常量,它将正常工作。

使用std::vectornew/delete

我不确定,但可能是因为矩阵的大小是动态的,编译器无法在编译时生成初始值设定项。

s[m][n]={0}

初始化只有在编译时知道矩阵的大小时才有效,你需要使用 memset 或循环来初始化这个矩阵。 使用memset非常简单:memset(s,0,m*m*sizeof(int))

当你声明数组s它的维度应该在编译时知道。 由于您没有显式初始化mn,它们都使用一些随机值初始化并用于数组声明s。 因此,您的s数组可能具有任何随机尺寸(可能是零(,并且在输入m并从cinn后,您可能只是打印一些未初始化的存储单元。

禁止以变量的形式分配静态矩阵/数组的大小。您必须在编译时给出大小或使用动态数组。

#include <iostream>
using namespace std;
int main()
{
int i, j, s[4][4] = { 0 };
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
cout << s[i][j] << " ";
}
cout << endl;
}
}

使用空括号 {} 初始化数组。默认情况下,这会将数组的所有元素初始化为 null。

相关文章: