我用C语言运行了这几行代码:
int tab[]={4,6,8,9,20};char *p; p=(char*)tab
int tab[]={4,6,8,9,20};
char *p;
p=(char*)tab
问题是如何用指针p打印20的值。所以我用了一个for循环来看看p是怎么回事
for(int i=0;i<20;i++){ printf("%d ",p[i]); }
for(int i=0;i<20;i++){
printf("%d ",p[i]);
}
我得到了这个输出:
4 0 0 0 6 0 0 0 8 0 0 0 9 0 0 0 20 0 0 0
我想知道这些零出现的逻辑。
thtygnil1#
几乎可以肯定,您使用的是int为4字节的体系结构,以及先存储“最小”字节的little-endian体系结构。因此,int值4存储为:
int
4
+----+----+----+----+| 4 | 0 | 0 | 0 |+----+----+----+----+
+----+----+----+----+
| 4 | 0 | 0 | 0 |
int值20存储为:
20
+----+----+----+----+| 20 | 0 | 0 | 0 |+----+----+----+----+
| 20 | 0 | 0 | 0 |
内存中的整个数组如下所示:
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+| 4 | 0 | 0 | 0 | 6 | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 9 | 0 | 0 | 0 | 20 | 0 | 0 | 0 |+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
| 4 | 0 | 0 | 0 | 6 | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 9 | 0 | 0 | 0 | 20 | 0 | 0 | 0 |
现在,当您将这20个字节作为字符进行迭代时(因此一次迭代一个字节),结果应该不再令人惊讶。
yqlxgs2m2#
在您的计算机上,sizeof和int是4字节,而sizeof和char根据定义是1。因此,使用p,您将逐字节打印int。
sizeof
char
1
p
关于这一点:
#include <stdio.h>#include <stdlib.h> int main(void) { int tab[] = {4, 6, 8, 9, 20}; char *p = 0; /* The type that & returns is a * pointer type, in this case, a * pointer to the 4th element of * the array. */ p = (char*) &tab[4]; /* As %d expects an int, we cast * p to an int *, and then * dereference it. */ printf("%d\n", *(int *)p); return EXIT_SUCCESS;}
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int tab[] = {4, 6, 8, 9, 20};
char *p = 0;
/* The type that & returns is a
* pointer type, in this case, a
* pointer to the 4th element of
* the array.
*/
p = (char*) &tab[4];
/* As %d expects an int, we cast
* p to an int *, and then
* dereference it.
printf("%d\n", *(int *)p);
return EXIT_SUCCESS;
编辑:上面的代码依赖于字节序。
2条答案
按热度按时间thtygnil1#
几乎可以肯定,您使用的是
int
为4字节的体系结构,以及先存储“最小”字节的little-endian体系结构。因此,
int
值4
存储为:int
值20
存储为:内存中的整个数组如下所示:
现在,当您将这20个字节作为字符进行迭代时(因此一次迭代一个字节),结果应该不再令人惊讶。
yqlxgs2m2#
在您的计算机上,
sizeof
和int
是4
字节,而sizeof
和char
根据定义是1
。因此,使用
p
,您将逐字节打印int
。关于这一点:
输出:
编辑:上面的代码依赖于字节序。