Accessing values in a 2D array incorrectly
-
12-02-2021 - |
题
I have a 2D array such as:
// construct initial **array
int **arr;
arr = new int* [SIZE];
for (int i = 0; i < SIZE; i++) {
arr[i] = new int[SIZE];
}
I am then filling the array with input from cin, and that is working fine. Yet when I go to access the values in the array by double for loop iteration, I get the incorrect values.
I have printed out the values as I am adding them in something like:
"Adding <int> to array position <row><col>"
For example, I am storing the ints {{1,2,3}, {4,5,6}, {7,8,0}}
, yet when I go to access them, I get the values {{49,50,51}, {52,53,54}, {55,56,48}}
.
I have a feeling that it's something trivial, I just have no idea where to look.
解决方案
It looks like you are storing the ASCII values of the numbers rather than their numeric values, for example the character 1
has ASCII value 49. Check that the variable you are using to read input is a numeric type and not char
.
其他提示
It looks to me like you're getting the ASCII values of the characters -- ie, 49 is '1', 50 is '2', etc.