Re: Pointer arithmetics in 2D arrays



Richard Heathfield wrote:
Army1987 said:

"Richard Heathfield" <rjh@xxxxxxxxxxxxxxx> ha scritto nel messaggio
news:3vmdnfaq96CmmtrbnZ2dnUVZ8tGqnZ2d@xxxxxxxxx
Army1987 said:
[snip]
int main(void)
{
int matrix[3][3] = { {157, 64, 13},
{ 0, -16, 128},
{ 54, 42, -23} }
int *p = &matrix[0][0]
Here's where you missed your semicolon. Incidentally, what is p for?
What's worse is that I missed *two* semicolons...

So you did.

(p is for the example below.)

Suppose I have int *p, *q; p = &matrix[0][0]; q = &matrix[1][0];
p += 3;

Um, yeah, you can do that, and you're now pointing one beyond the end of matrix[0], which is legal as long as you don't dereference.

Now p and q are equal.

I don't think you're allowed to compare them, are you? After all, one of them is pointing into-or-one-past-the-end-of matrix[0], whereas the other is pointing into-or-one-past-the-end-of matrix[1], and these are different objects.

It's all right to compare them for equality or inequality,
using == or !=. p==q is true, but p-q is undefined behavior!

> (I must say I find the Standard rather silly at this
> point, given that arrays are guaranteed to be contiguous.)

I imagine that the Standard is trying to leave some leeway
for implementations that are able to check array bounds. At
least one implementation has done such checking, essentially by
giving each pointer value a "pedigree" describing the legitimate
bounds within which it points. When you derive a new pointer from
an old one (as in p+=3), the pedigree is carried along unchanged.
Thus, although p and q compare equal they have different pedigrees:
p is derived from matrix[0] and q from matrix[1], and the allowed
ranges of the two pointers are different even though their values
are identical.

--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxx
.



Relevant Pages

  • Re: Question on
    ... If you terminate the above statement with a semicolon, ... initialises the pointer s to be a null pointer. ... but only because it it is confusing. ...
    (comp.lang.c)
  • Re: Question on
    ... If you terminate the above statement with a semicolon, ... initialises the pointer s to be a null pointer. ... but only because it it is confusing. ...
    (comp.lang.c)
  • Re: Question on
    ... If you terminate the above statement with a semicolon, ... initialises the pointer s to be a null pointer. ... (decimal int) ...
    (comp.lang.c)
  • Re: how is the array offset determined?
    ... Presumably you didn't mean the semicolon there. ... I'm assuming you intend x to be an integer. ... value is neither array nor pointer". ...
    (comp.lang.c)