#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int a[4][5] =
{
{1,1,0,1,0},
{0,0,0,0,0},
{0,1,0,0,0},
{1,0,1,1,0}
};
int *ptr = &a[0][0];
for (; ptr < ptr+19; ptr++)
{
printf("%d ", *ptr);
}
return 0;
}
Why does this code not work? as far as i know 2D arrays are stored in row major order so like this:
[1,1,0,1,0]-[0,0,0,0,0]-[0,1,0,0,0]-[1,0,1,1,0]
So if i started at &a[0][0] and incremented it by 1 each time until it has been incremented to the last element why does this not work?
ptris always less thanptr+19, at least until the pointer runs off the end of the address space and wraps around, but it is likely to be pointing to invalid memory before that happens.ptr < ptr+19you aren't allowed to de-reference arrays in this manner. You go out of bounds in the array access and it's undefined behavior. The compiler is allowed to go nuts and generate strange code or a crashing program.