gpt4 book ai didi

c - 如何向初学者解释 C 指针(声明与一元运算符)?

转载 作者:太空狗 更新时间:2023-10-29 16:14:24 26 4
gpt4 key购买 nike

我最近有幸向 C 编程初学者解释指针,并偶然发现了以下困难。如果您已经知道如何使用指针,这可能看起来根本不是问题,但请尝试以清醒的头脑看下面的示例:

int foo = 1;
int *bar = &foo;
printf("%p\n", (void *)&foo);
printf("%i\n", *bar);

对于绝对初学者来说,输出可能会令人惊讶。在第 2 行,他/她刚刚声明 *bar 为 &foo,但在第 4 行,事实证明 *bar 实际上是 foo 而不是 &foo!

您可能会说,混淆源于 * 符号的歧义:在第 2 行中,它用于声明指针。在第 4 行中,它用作一元运算符,用于获取指针指向的值。两个不同的东西,对吧?

但是,这种“解释”对初学者一点帮助都没有。它通过指出细微的差异引入了一个新概念。这不是正确的教学方法。

那么,Kernighan 和 Ritchie 是如何解释的?

The unary operator * is the indirection or dereferencing operator; when applied to a pointer, it accesses the object the pointer points to. […]

The declaration of the pointer ip, int *ip is intended as a mnemonic; it says that the expression *ip is an int. The syntax of the declaration for a variable mimics the syntax of expressions in which the variable might appear.

int *ip 应该读成“*ip 将返回一个 int”?但是为什么声明之后的赋值不遵循这种模式呢?如果初学者想初始化变量怎么办? int *ip = 1(阅读:*ip 将返回一个 intint1 ) 将无法按预期工作。概念模型似乎并不连贯。我在这里遗漏了什么吗?


编辑:它试图summarize the answers here .

最佳答案

简写的原因:

int *bar = &foo;

在您的示例中可能会造成混淆,因为很容易将其误读为等同于:

int *bar;
*bar = &foo; // error: use of uninitialized pointer bar!

当它实际上意味着:

int *bar;
bar = &foo;

这样写,变量声明和赋值分开,就没有这种混淆的可能性,并且在您的 K&R 引用中描述的 use ↔ 声明并行性非常有效:

  • 第一行声明了一个变量bar,这样*bar就是一个int

  • 第二行将foo的地址赋值给bar,使得*bar(一个int) foo 的别名(也是 int)。

在向初学者介绍 C 指针语法时,最初坚持这种将指针声明与赋值分开的风格可能会有所帮助,并且只有在基本概念C 中的指针使用已充分内化。

关于c - 如何向初学者解释 C 指针(声明与一元运算符)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27484168/

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