I'm new to C and learning it for a class right now. We are currently working on a little project and we are supposed to use pointer arithmetic to access arrays as opposed to the standard [] way.
For some reason, I can use it just fine on the first loop (see code) but when I use it in the second, it doesn't produce the same outcome as if I were to use the standard [] way.
for (int i = 0; i < size; i ) {
for (int j = 0; j < size; j ) {
int num = *(*array i) j;
//Irrelevant code
}
}
for (int i = 0; i < size; i ) {
for (int j = 0; j < size; j ) {
int num = array[j][i]; // Error comes if I do *(*array j) i;
//Irrelevant code
}
}
I don't know if I am missing something here but why would calling the array using pointer arithmetic be different between the 2 loops?
CodePudding user response:
The equivalence between subscripts and pointer notation is:
a[i] == *(a i)
You are using (*a i)
in place of the correct *(a i)
.
I believe your first set of loops should read:
for (int i = 0; i < size; i ) {
for (int j = 0; j < size; j ) {
int spot = *(*(board i) j);
for (int k = j 1; k < size; k ) {
if (spot == *(*(board i) k) && spot > 0) {
return 0;
}
}
}
}
However, since you've not provided an MCVE (Minimal, Complete, Verifiable Example — or MRE or whatever name SO now uses) or an SSCCE (Short, Self-Contained, Correct Example — the same idea by a different name), I can't easily test the code.
Also, now you know why it is better to use the explicit subscript notation; it is a lot harder to get it wrong.