pointer's problem

Started by
11 comments, last by remi 21 years, 5 months ago
quote:Original post by Anonymous Poster
*b == A[0][0] *b+1 == A[0][1] *b+2 == A[1][0] *b+3 == A[2][2]


Also, AP''s WOULD be a good representation of how to access the array through pointer notation except he screwed up his operator precidence. The CORRECT way of doing pointer notation would have been

*(b)
*(b+1)
*(b+2)
*(b+3)

He left out the parenthesis, so rather than accessing the different elements you would have just been adding values to the first element and actually wouldn''t have been doing pointer arithmentic at all.

Another way you could look at accessing the array is, using that same logic, the pattern

int a[numrows][numcols]

a[row][column] = &a[0][0] + row * numcols + column

this can be better understood by looking at the matrix a as an array of numrows arrays of length numcols, so every numcols worth of elements is the beginning of the next dimension. row * numcols gives you the 0th element of that row and adding column gives you the colum of that array.

Only use that method if you don''t know the dimensions of the array at runtime (IE if you dynamically allocate the array), or if you are passing the array to a function in which the lengths of the dimensions can vary.

Again, the original method I mentioned is probably the best way

int (*b)[2][2]

and it''s also the most readable when accessing elements -- ESPECIALLY when dealing with arrays of more than 2 dimensions (in which manually calculating the address becomes very drawn out and unreadable).
Advertisement
Thanx all for anyhelp u gave, I tried to make a resume of all the methods u proposed and then according to the specific problem i had i decided to use this:
int a[VER_NUM][HOR_NUM];
int *b;
b=a;
And then to get the value of a[y][x], i just need to do:
b[y*VER_NUM+x]. It works and it''s quite smart for what i''m doing.

Nevertheless i tried something Matt Calabrese proposed but when doing this:
int (*b)[2][2];
b = &a
Then b[0][0] = 1; becomes an invalid code, because b[0][0] is like a pointer.

Once again thanx all
"...and we all know what "undefined" means: it means it works during development, it works during testing, and it blows up in your most important customers' faces."----------Scott Meyers, "Effective C++"
Oh, woops.

Yeah, you can do it the way I mentioned, but I forgot that array pointers aren''t auto-dereferencing (unlike functions).

My way will work, how every you do have to explicitly dereference:

(*b)[0][0] = 1

will work.

However, there is a much easier way to do it, without having to dereference it. Do this:

int (*b)[2] = a; // Which for us will represent a pointer to an array of 1 dimensional integer arrays of length 2

you will now be able to do:

b[0][0] = 1;

with not problem at all.

This topic is closed to new replies.

Advertisement