Theo Walton
Theo Walton

Reputation: 1105

segfault when accessing array after typecasting to a different type

so I know you can do things like this:

 char c[4];
 int *p;

 p = (int*)c;
 p[0] = 1;

to set all the character values at once. But I went a step further and did:

char c[1][4];
int **p;

p = (int**)c;
p[0][0] = 1;

and it segfaults. Could someone explain why this is happening?

Upvotes: 3

Views: 83

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140276

you were lucky in your first example: alignment constraints on some CPUs (ex: on legacy 68000) could have segfaulted right away... Not to mention not portable code because of endianness issue.

That said, c[1][4] isn't an array of pointers. It's a 2D array (of 4 bytes storage). So dereferencing it twice like you're doing is bound to fail (your previous technique probably "works", though).

Lying to the compiler like this isn't really an option. Also note that int isn't guaranteed to be 4 bytes long, so better use standardized types like uint32_t (unsigned 32-bit integer from stdint.h)

To set data faster, you could use memcpy, example:

uint32 v = 1;
memcpy(c,&v,sizeof(v));

Upvotes: 4

Related Questions