简体   繁体   中英

Assignment of an integer variable address to character pointer

Following is a piece of C++ code which assigns integer variable address to character pointer.

int ia = (1<<25) + (1<<24) + (1<<17) + (1<<8) + 4;
char *cArr = (char *)(&ia);
int i;
for(i = 0; i < 4; i++){ cout << (int)cArr[i] << endl; }

I have chosen the integer variable so that the MSB byte can have a value of 3, the next value of 2, the next a value of 1 and the LSB byte a value of 4.

Now when I assign the integer's address to a character pointer then I get the following result:

cArr[0] = 4
cArr[1] = 1
cArr[2] = 2
cArr[3] = 3

I have some questions regarding this result:

  1. Is it always that the LSB byte will get the first address irrespective of the machine on which I am working.
  2. Has the result something to do with Little Endian and Big Endian. Also I am looking for some basic tutorial which can get me the basics of Little Endian and Big Endian.
  3. Has the result something to do with how the stack grows on a machine.

By the way I work on a windows PC

1). No that depends upon the computer architecture and hardware. Here is the table that can be taken as a reference. 在此处输入图片说明

2). Basic tutorial. Hope this would suffice. http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/endian.html

3).No nothing to do with stack as you see from table windows follow, Little Endian and hence LSB place first.

let me know if that answers you.

Bye!

  1. No. The results depends on your system hardware type. Only little-endian machines get your results.

  2. Just as question 1, this indeed is determined by little-endian or big-endian. Here is a comprehensive introduction on endian. http://www.yolinux.com/TUTORIALS/Endian-Byte-Order.html

  3. There is nothing to do with stack in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM