为什么第一行会出现零以外的其他值?
Why some other value than zero is coming in first row?
我正在尝试使用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
如果你做n
,m
常量,它将正常工作。
使用std::vector
或new
/delete
。
我不确定,但可能是因为矩阵的大小是动态的,编译器无法在编译时生成初始值设定项。
s[m][n]={0}
初始化只有在编译时知道矩阵的大小时才有效,你需要使用 memset 或循环来初始化这个矩阵。 使用memset非常简单:memset(s,0,m*m*sizeof(int))
当你声明数组s
它的维度应该在编译时知道。 由于您没有显式初始化m
和n
,它们都使用一些随机值初始化并用于数组声明s
。 因此,您的s
数组可能具有任何随机尺寸(可能是零(,并且在输入m
并从cin
n
后,您可能只是打印一些未初始化的存储单元。
禁止以变量的形式分配静态矩阵/数组的大小。您必须在编译时给出大小或使用动态数组。
#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。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 从C++dll访问C#中的一行主要参数
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 在其他文件中创建类时在 c++ 项目中不起作用
- 类与私有变量的其他类之间的线程安全性
- 在C++中,我如何接受不同于同一行的用户输入
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- GlobalAlloc而不是其他分配方法
- 如何从一行中读取特定数量的字符?(C++)
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 当一行中只有一个"#"而没有其他内容时,C++预处理器会做什么?
- 在一行中输入具有其他输入类型的多个单词字符串
- 最后一行欧普特两个组合输出问题?如果其他语句
- 如何逐字读取文件的第一行,而将其他行作为逐行存储在变量中