V
vippstar
I had once posted a message here on comp.lang.c, which asked if a
multi-dimensional array can be treated as a single-dimension array.
Message-ID: <38b37f10-252e-48f8-bffa-
(e-mail address removed)>
From what I've gathered, it is undefined behavior. Code such as:
#include <stdio.h>
int main(void) {
int m[2][2] = {0}, *p = m, i = 0;
while(i++ < 4) printf("%d\n", *p++);
return 0;
}
Invokes undefined behavior, an optimizer may ignore references after
(int *)m[0] + 1, because the object m[0] "contains" two ints only.
However I have this query now:
#include <stdint.h>
/* ... */
int m[2][2];
uintptr_t k = (uintptr_t)m;
uintptr_t j = (uintptr_t)m[1];
It is guaranteed that k + sizeof (int) * 2 == j. It's also guaranteed
that (int *)j == (int *)k.
Therefore, this code is correct:
#include <stdio.h>
#include <stdint.h>
int main(void) {
int m[2][2] = {0}, i = 0;
uintptr_t k = (uintptr_t)m;
while(i++ < 4) {
printf("%d\n", *(int *)k);
k += sizeof (int);
}
return 0;
}
There's three possibilities:
* The former code is not incorrect, unlike what I've been told
* The latter code is incorrect, to my surprise
* The former is incorrect, while the latter is correct.
Which one of them is it?
multi-dimensional array can be treated as a single-dimension array.
Message-ID: <38b37f10-252e-48f8-bffa-
(e-mail address removed)>
From what I've gathered, it is undefined behavior. Code such as:
#include <stdio.h>
int main(void) {
int m[2][2] = {0}, *p = m, i = 0;
while(i++ < 4) printf("%d\n", *p++);
return 0;
}
Invokes undefined behavior, an optimizer may ignore references after
(int *)m[0] + 1, because the object m[0] "contains" two ints only.
However I have this query now:
#include <stdint.h>
/* ... */
int m[2][2];
uintptr_t k = (uintptr_t)m;
uintptr_t j = (uintptr_t)m[1];
It is guaranteed that k + sizeof (int) * 2 == j. It's also guaranteed
that (int *)j == (int *)k.
Therefore, this code is correct:
#include <stdio.h>
#include <stdint.h>
int main(void) {
int m[2][2] = {0}, i = 0;
uintptr_t k = (uintptr_t)m;
while(i++ < 4) {
printf("%d\n", *(int *)k);
k += sizeof (int);
}
return 0;
}
There's three possibilities:
* The former code is not incorrect, unlike what I've been told
* The latter code is incorrect, to my surprise
* The former is incorrect, while the latter is correct.
Which one of them is it?