Kun*_*ade -4 c arrays pointers
这是该计划: -
#include<stdio.h>
int main()
{
int a[8]={1,2,3,4,5,6,7,8,9},i;
char* p;
p=(char*)a;
printf("%d",*p);
for( i=0;i<32;i++)
{
p=p+1;
printf("%d",*p);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出: -
$ ./a.out
100020003000400050006000700080000
Run Code Online (Sandbox Code Playgroud)
为什么输出是这样的?
为什么有三个零后跟数组的值?
char指针增加1个字节.存储在内存中的二进制表示形式为0000000 00000000 00000000 00000001.是吗?所以输出应该像0 0 0 1.如果错误请解释.
解
char通常是1个字节,而int通常是4个字节.在内存中如果需要增加char pointer4次以完全增加a int.
更改
char* p;
p=(char*)a;
Run Code Online (Sandbox Code Playgroud)
至:
int* p;
p=(int*)a;
Run Code Online (Sandbox Code Playgroud)
这将删除所有零
也改变
int a[8]={1,2,3,4,5,6,7,8,9},i;
Run Code Online (Sandbox Code Playgroud)
至:
int a[9]={1,2,3,4,5,6,7,8,9},i;
Run Code Online (Sandbox Code Playgroud)
因为你没有分配足够的空间和改变
printf("%d",*p);
for( i=0;i<32;i++)
{
p=p+1;
printf("%d",*p);
}
Run Code Online (Sandbox Code Playgroud)
至:
for(i=0; i<9; i++)
{
printf("%d",*p);
p=p+1;
}
Run Code Online (Sandbox Code Playgroud)
C和大多数语言中的内存映射可视化数组只是存储在连续内存位置的元素.int array[2] = {1,2}在内存中看起来像这样:
// Assuming array starts at location 0x000 (in hex)
// Keep in mind a byte is 8 bits so a byte can contain values from 0x00 to 0xff
location: value:
0x00 = [0x01] // first byte of first int
0x01 = [0x00] // second byte of first int
0x02 = [0x00] // third byte of first int
0x03 = [0x00] // fourth byte of first int
0x04 = [0x02] // first byte of second int
0x05 = [0x00] // second byte of second int
0x06 = [0x00] // third byte of second int
0x07 = [0x00] // fourth byte of second int
Run Code Online (Sandbox Code Playgroud)
如您所见,int占用4个字节.int *增加4个内存位置,这将使您获得下一个整数值.在你的情况下,增加a之后char *,你只增加四分之一int并打印出零(其中3个).
如果您尝试int array[2] = {256, 2}使用它进行迭代char *,我相信您会打印出来:
0 1 0 0 2 0 0 0
这是因为256等于0x100因此它不能存储在一个字节中并且必须利用第一个字节内的第二个字节int.内存映射将如下所示:
location: value:
0x00 = [0x00] // first byte of first int
0x01 = [0x01] // second byte of first int
0x02 = [0x00] // third byte of first int
0x03 = [0x00] // fourth byte of first int
0x04 = [0x02] // first byte of second int
0x05 = [0x00] // second byte of second int
0x06 = [0x00] // third byte of second int
0x07 = [0x00] // fourth byte of second int
Run Code Online (Sandbox Code Playgroud)