【问题标题】:Error in initializing 2-D array values to '0' in c++, giving garbage values在 C++ 中将二维数组值初始化为“0”时出错,给出垃圾值
【发布时间】:2020-07-23 09:57:12
【问题描述】:

以下是代码,我已经一一尝试了 cmets 中提到的所有其他样式,但没有一个可以删除垃圾值,虽然“jugaad”有效,但性能不佳。不知道怎么回事!

#include <bits/stdc++.h>
using namespace std;
int main() {
int n,m;
cin>>n>>m;
//    Other styles
//    int data[n+1][m+1] = {0,0};
//    int data[n+1][m+1] = {0};
//    int data[n+1][m+1] = {{0,0}};
int data[n][m] = {0};
//    Jugaad start:
for(int i=0;i<m;i++){
    data[0][i] = 0;
}
// Jugaad end
cout<<"\n";
    for(int x=0;x<n;x++){
        for(int y=0;y<m;y++){
            cout<<data[x][y]<<"\t";
        }
        cout<<"\n";
    }
cout<<"\n";
return 0;
}    

Screenshot of code and output

【问题讨论】:

  • 不是答案,int data[n][m] 不是有效的 C++,数组大小必须在编译时知道。如果它适合你,那么你的编译器支持它作为扩展。您可能应该使用std::vector

标签: c++ arrays c++11


【解决方案1】:
for(int i=0;i<n;i++)
{
    for(int j=0;j<n;j++)
      {
         data[i][j] = 0;
      }
 ``}

这会将数组的所有值设置为零

【讨论】:

  • 是的,但在竞争性编程方面表现不佳,为什么:int arr[n][m] = {0};不工作?
  • @PrashantRawat int arr[n][m] = {0}; 不是有效的 C++。数组的大小必须在编译时知道。因此,在 C++ 中没有这方面的规则。如果你的编译器支持它,你应该检查你的编译器的文档。不知道编译器和编译器版本,我们无能为力。
猜你喜欢
  • 2015-02-28
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 2022-11-14
  • 2021-01-12
相关资源
最近更新 更多