gpt4 book ai didi

c - 指针运算 : char pointer as a member of a struct

转载 作者:太空宇宙 更新时间:2023-11-04 06:57:44 24 4
gpt4 key购买 nike

我从 K&R(第 133 页)中拿了一个 structure 的例子,并在 pointer 上尝试了一些 pointer 算法到 结构的数组

#include <stdio.h>
// struct example from K&R
struct key {
char *word;
int count;
}keytab[] = {
"auto",0,
"break",0,
"const",0,
/*.....*/
"case",0
};
int main () {
struct key *ptr1 = keytab;
printf("%d\n",sizeof(struct key));

//check1
printf("%s\n",ptr1++->word); //1
printf("%s\n",ptr1->word); //2

//check2
printf("%s\n",++ptr1->word); //3
printf("%s\n",++ptr1->word); //4

//check3
printf("%s\n",ptr1++->word); //5
printf("%s\n",ptr1->word); //6 ??
}

输出:

8
auto
break
reak
eak
eak
const

借助运算符优先级,我可以理解 3rd4th printf 的输出。

但是当涉及到 5th6th printf 时,ptr1 在这里是如何递增的?程序的输出显示与 1st & 2nd printf 类似的行为。如果 ptr1 以一个结构大小(此处为 8 字节)递增,那么它如何将自身与 keytab[2] 的开头对齐。

我可能理解错了,或者最后这个查询可能无效,请解释!

感谢您的帮助!

最佳答案

If ptr1 increments in step of one struct size (here 8 bytes) then how it aligns itself to the starting of a keytab[2].

但是 ptr1 总是 指向 keytab 的一个元素。不允许中途指向一个元素,这种情况永远不会发生。

您看到 reakeak 的原因是 ptr1 指向的 key 表条目已就地更改。

也就是说,++ptr1->word 不会改变ptr1根本。您可以检查 - 只需在前后打印它的值。该表达式更改 word inside 您的 key 表的值。在第 3 行之后,keytab[1].word 已更改(递增)因此它指向 "reak"

当您最终再次递增 ptr1 时(就在打印#5 之后),您仍然将它从 &keytab[1] 递增到 &keytab[2 ]。您修改 keytab[1] 内部的事实根本不会影响它。

I could understand the output of 3rd and 4th printf with the help of operator precedence

看来您正确地意识到了其中的大部分内容,但忽略了更改 ptr1->word 不会影响 ptr1 本身的值。

关于c - 指针运算 : char pointer as a member of a struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42009358/

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