'Array gives different values in main() and in a function() [closed]
I am trying to store a 1d array that stores random numbers into another 2d array.
So as you can see, I am trying to store the passed random array a1 from the main() function to the test() function. And then I am adding it into p[][]. But I don't know why when I am trying to output the array p[][] in the main function, it is giving different values from what I have passed to it!
I would highly appreciate your help. As I need to reuse the stored data in p[][] in order to finish my task.
Code:
#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;
}
Output:
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
Solution 1:[1]
You have two different p arrays: One in main and one global. The print loop in main is accessing the local p in main while test accesses the global one. That means only the global p gets filled with data and main is stuck with a different array that wasn't filled with data.
Remove the int p[9][9]; in main. That line creates a second array that shadows the first (global) one.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jonathan S. |
