I have an array of 50 char
s:
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?
I have an array of 50 char
s:
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?
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 */