在c中将int数组转换为char指针

5rgfhyps  于 2023-01-08  发布在  其他
关注(0)|答案(2)|浏览(242)

我用C语言运行了这几行代码:

  1. int tab[]={4,6,8,9,20};
  2. char *p;
  3. p=(char*)tab

问题是如何用指针p打印20的值。
所以我用了一个for循环来看看p是怎么回事

  1. for(int i=0;i<20;i++){
  2. printf("%d ",p[i]);
  3. }

我得到了这个输出:

  1. 4 0 0 0 6 0 0 0 8 0 0 0 9 0 0 0 20 0 0 0

我想知道这些零出现的逻辑。

thtygnil

thtygnil1#

几乎可以肯定,您使用的是int为4字节的体系结构,以及先存储“最小”字节的little-endian体系结构。
因此,int4存储为:

  1. +----+----+----+----+
  2. | 4 | 0 | 0 | 0 |
  3. +----+----+----+----+

int20存储为:

  1. +----+----+----+----+
  2. | 20 | 0 | 0 | 0 |
  3. +----+----+----+----+

内存中的整个数组如下所示:

  1. +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
  2. | 4 | 0 | 0 | 0 | 6 | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 9 | 0 | 0 | 0 | 20 | 0 | 0 | 0 |
  3. +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+

现在,当您将这20个字节作为字符进行迭代时(因此一次迭代一个字节),结果应该不再令人惊讶。

展开查看全部
yqlxgs2m

yqlxgs2m2#

在您的计算机上,sizeofint4字节,而sizeofchar根据定义是1
因此,使用p,您将逐字节打印int

  • "问题是如何使用指针p打印20的值。"*

关于这一点:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main(void)
  4. {
  5. int tab[] = {4, 6, 8, 9, 20};
  6. char *p = 0;
  7. /* The type that & returns is a
  8. * pointer type, in this case, a
  9. * pointer to the 4th element of
  10. * the array.
  11. */
  12. p = (char*) &tab[4];
  13. /* As %d expects an int, we cast
  14. * p to an int *, and then
  15. * dereference it.
  16. */
  17. printf("%d\n", *(int *)p);
  18. return EXIT_SUCCESS;
  19. }

输出:

  1. 20

编辑:上面的代码依赖于字节序。

展开查看全部

相关问题