3

I have an array of 50 chars:

char arr[50];

I'm told that in arr[1] till arr[4], there is an int I need to get.

I did :

int *p = (int *)(arr+1);

return *p;

I was told it's a mistake. Why?

Maroun
  • 94,125
  • 30
  • 188
  • 241
user1047069
  • 935
  • 2
  • 13
  • 25
  • 5
    Because it violates the [strict aliasing rule](http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule). –  Nov 24 '13 at 20:51
  • The question's underspecified here. Certainly what H2CO3 says is true, but your instructor may have meant four text digits, or may have been talking about endianness in class. edit: and I see you put the alignment tag yourself, is there a reason you don't say why that's not a good enough answer here? – jthill Nov 24 '13 at 21:02

1 Answers1

0

On my system, sizeof(char)=1, sizeof(int)=4.

The root of the issue is that you are casting to a pointer to int (int *), which is masking the true alignment of the underlying type char. Assuming a 4-byte int, the compiler tries to access 4 bytes instead of 1.

Given:

char arr[] = "ABCDEFGHI";

Then your code yields:

int *p = (int *)(arr+1); /* *p = 1162101570, interpreting "BCDE" as int */

In order to take advantage of C's automatic type conversion, you need something more like this:

int p = (int)(*(arr+1)); /* p = 66, the ASCII code for 'B' */

or, less obscure, and more technically correct based on your original declaration of arr,

int p = (int)arr[1]; /* p = 66 */

but really, this is all you need:

int p = arr[1]; /* p = 66 */
codnodder
  • 1,674
  • 9
  • 10