gpt4 book ai didi

c - 根据这段 C 代码,指针和变量的值是多少?

转载 作者:行者123 更新时间:2023-11-30 21:34:19 26 4
gpt4 key购买 nike

我对指针感到困惑......为什么 ipp 的值不是 88?如果 *ipp=88 则显示垃圾? *ipp 也可以这样说吗?它还显示垃圾,这是为什么?

您能解释一下指针在我的例子中是如何工作的吗?为什么*ip1的值为97(它是如何从公式*ip1 * 7 + b得出的)?

int a = 11, b = 20;
int x, y;

int *ip1 = &a;
int *ip2 = &x;

int **ipp = &ip2;

*ip2 = *ip1 * 7 + b;

ip1 = ip2;
ip2 = &y;

**ipp = 88;
*ipp = &b;

最佳答案

这里有一些代码显示了正在发生的事情(详细程度令人难以忍受):

#include <stdio.h>

int main(void)
{
int a = 11;
int b = 20;
int x = -1;
int y = -1;
int *ip1 = &a;
int *ip2 = &x;
int **ipp = &ip2;

printf("Addresses:\n");
printf(" &a = %p\n", (void *)&a);
printf(" &b = %p\n", (void *)&b);
printf(" &x = %p\n", (void *)&x);
printf(" &y = %p\n", (void *)&y);
printf(" &ip1 = %p\n", (void *)&ip1);
printf(" &ip2 = %p\n", (void *)&ip2);
putchar('\n');
printf("%3s %3s %3s %3s %14s %14s %14s %4s %4s %5s\n",
"a", "b", "x", "y", "ip1", "ip2", "ipp", "*ip1", "*ip2", "**ipp");
printf("%3d %3d %3d %3d %14p %14p %14p %4d %4d %5d\n",
a, b, x, y, (void *)ip1, (void *)ip2, (void *)ipp, *ip1, *ip2, **ipp);

*ip2 = *ip1 * 7 + b;
printf("%3d %3d %3d %3d %14p %14p %14p %4d %4d %5d\n",
a, b, x, y, (void *)ip1, (void *)ip2, (void *)ipp, *ip1, *ip2, **ipp);

ip1 = ip2;
printf("%3d %3d %3d %3d %14p %14p %14p %4d %4d %5d\n",
a, b, x, y, (void *)ip1, (void *)ip2, (void *)ipp, *ip1, *ip2, **ipp);

ip2 = &y;
printf("%3d %3d %3d %3d %14p %14p %14p %4d %4d %5d\n",
a, b, x, y, (void *)ip1, (void *)ip2, (void *)ipp, *ip1, *ip2, **ipp);

**ipp = 88;
printf("%3d %3d %3d %3d %14p %14p %14p %4d %4d %5d\n",
a, b, x, y, (void *)ip1, (void *)ip2, (void *)ipp, *ip1, *ip2, **ipp);

*ipp = &b;
printf("%3d %3d %3d %3d %14p %14p %14p %4d %4d %5d\n",
a, b, x, y, (void *)ip1, (void *)ip2, (void *)ipp, *ip1, *ip2, **ipp);

return 0;
}

它只是打印除 ipp 之外的所有变量的地址 - 代码中的任何表达式都不会使用它的地址。然后,它打印每个普通整数、每个指针以及各种取消引用的指针的值。

示例输出

Addresses:
&a = 0x7fff5bacd4f0
&b = 0x7fff5bacd4f4
&x = 0x7fff5bacd4f8
&y = 0x7fff5bacd4fc
&ip1 = 0x7fff5bacd500
&ip2 = 0x7fff5bacd508

a b x y ip1 ip2 ipp *ip1 *ip2 **ipp
11 20 -1 -1 0x7fff5bacd4f0 0x7fff5bacd4f8 0x7fff5bacd508 11 -1 -1
11 20 97 -1 0x7fff5bacd4f0 0x7fff5bacd4f8 0x7fff5bacd508 11 97 97
11 20 97 -1 0x7fff5bacd4f8 0x7fff5bacd4f8 0x7fff5bacd508 97 97 97
11 20 97 -1 0x7fff5bacd4f8 0x7fff5bacd4fc 0x7fff5bacd508 97 -1 -1
11 20 97 88 0x7fff5bacd4f8 0x7fff5bacd4fc 0x7fff5bacd508 97 88 88
11 20 97 88 0x7fff5bacd4f8 0x7fff5bacd4f4 0x7fff5bacd508 97 20 20

确保您理解所看到的内容 - 当所有数据都这样呈现时,将这些点连接起来并不困难。

关于c - 根据这段 C 代码,指针和变量的值是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35966221/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com