数组在main()和function()中给出不同的值

  • 本文关键字:function main 数组 c++ arrays
  • 更新时间 :
  • 英文 :


我正在尝试将一个存储随机数的1d数组存储到另一个2d数组中。

如您所见,我正在尝试将传递的随机数组a1main()函数存储到test()函数。然后我将它添加到p[][]中。但我不知道为什么当我试图在主函数中输出数组p[][]时,它给出的值与我传递给它的值不同!

我非常感谢你的帮助。因为我需要重用p[][]中存储的数据才能完成我的任务。

代码:

#include <iostream>
#include <cstring>
using namespace std;

int p[9][9];
void test(int arr[], int rowCount){

for(int j=0; j<9; j++){
p[rowCount][j]=arr[j];
cout << p[rowCount][j] << " ";
}
cout <<endl;

}
int main()
{
int a1[9];
int p[9][9];

int rowCount=0;

int no = 9;
while(no!=0){
for(int i=0; i<9; i++){
a1[i] = rand()%100;
}
test(a1, rowCount++);
no--;
}

for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
cout<<p[i][j] << " ";
}
cout << endl;
}


return 0;
}

输出:

P[][] array in test()
41 67 34 0 69 24 78 58 62
64 5 45 81 27 61 91 95 42
27 36 91 4 2 53 92 82 21
16 18 95 47 26 71 38 69 12
67 99 35 94 3 11 22 33 73
64 41 11 53 68 47 44 62 57
37 59 23 41 29 78 16 35 90
42 88 6 40 42 64 48 46 5
90 29 70 50 6 1 93 48 29

P[][] array in main()
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460

您有两个不同的p数组:一个在main中,一个在global中。打印循环主要访问本地p,而test访问全局。这意味着只有全局p被数据填充,main被一个没有被数据填充的不同数组卡住。

主要卸下int p[9][9];。这一行创建了第二个数组,阴影化为第一个(全局)数组。

相关内容

最新更新