c - treating an array as a single variable -
code 1:
. . int main() { char ch1[3]; ch1[0]=ch1[1] = null; ch1[2]=0x01; ch1[2] = ch1[2]<<2; printf("%u", ch1[2]); system("pause"); homecoming 0; } . . the output of code:1 4 (as expected).
code 2:
. . int main() { char ch1[3]; ch1[0]=ch1[1] = null; ch1[2]=0x01; *ch1 = *ch1<<2; printf("%u", ch1[2]); system("pause"); homecoming 0; } . . but output of code:2 1 not expected! in line 6 of code:2, modification done changing ch1[2] = ch1[2]<<2; *ch1 = *ch1<<2;. have tried treating char array 1 numerical value , have done << operation; believe method incorrect. there right method treat array single numerical value basic mathematical operations?
i have changed code following:
int main() { char ch1[3]; ch1[0]=ch1[1] = null; ch1[2]=0x01; *(ch1+2) = *(ch1+2)<<9; printf("%u", ch1[1]); system("pause"); homecoming 0; } now output:0. shouldn't getting output 2 (i.e. 2^(9-8))? still, how treat array single numerical value?
right; actual question if possible treat array single value or not; considering ch1[0], ch1[1], ch1[2] single block of memory of 24 bits.
the type of pointer important ch1 similar pointer char- char*. when *ch1 refering char ch1 pointing at. if want treat entire array number need cast integer, problematic because array has 3 bytes, , integer has 4, top byte of x in illustration below pointing at, undefined
int main() { char ch1[3]; ch1[0]=ch1[1] = 0; ch1[2]=0x01; int *x = (int*)ch1; *x <<= 2; printf("%u", ch1[2]); system("pause"); homecoming 0; } c arrays pointers operators
No comments:
Post a Comment