c - 如何理解指针 (*) 和寻址 (&) 运算符的概念?

标签 c pointers pass-by-reference pass-by-value call-by-value

我试图理解这两个运算符的意义,所以我为此编写了这段代码。

#include <stdio.h>
#include <string.h>

int main()
{
    char *mnemonic, *operands;

    mnemonic = "add";
    operands = "five to two";

    analyse_inst(mnemonic, operands);

}

void analyse_inst(char mnemonic, char operands)
{
    printf("%s", mnemonic);
    printf("%s", operands);
}

但是,我注意到它不会工作,除非我将 analyse_inst() 函数的参数更改为 analyse_inst(char * mnemonic, char * operands),这意味着我将传递指向函数的指针。但为什么需要这样呢?

此外,我查找了“通过引用传递”。根据 tutorialspoint.com,它的定义:

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.

据此,我了解到通过引用传递一个变量然后修改该值将意味着函数外部的同一个变量也会被更改;而按值传递变量不会更改位于函数外部的相同变量。

我哪里出错了吗?

如何修改我的代码,以便通过引用传递这两个变量?

(附:我已经阅读了关于同一主题的其他 Stack Overflow 线程,但如果有人能在我编写的代码的上下文中解释它,我将不胜感激)

最佳答案

which means that I will be passing pointers to the function. But why is that required?

因为您在 main 中拥有的是指针,而 printf("%s" 期望的是 char*

“按引用传递”是编程中的一个广义术语,意思是传递地址而不是对象的副本。在您的情况下,您将指针传递给每个字符串的第一个元素,而不是复制整个字符串,因为那样会浪费执行时间和内存。

所以虽然字符串本身可以说是“按引用传递”,但严格来说 C 实际上只允许按值传递参数。 指针本身 是按值传递的。您的函数参数将是您在 main() 中分配的指针的副本。但它们指向与 main() 中的指针相同的字符串。

From that, I got that passing a variable by reference and then modifying that value would mean that the same variable outside the function would be changed as well;

确实,您可以通过指针从函数内部更改字符串,然后它会影响 main() 中的字符串。但在这种情况下,您没有分配任何内存来修改 - 您将尝试修改字符串文字 "...",这将是一个错误。如果要修改字符串,则应该在 main() 中将它们声明为数组:char mnemonic[] = "add";

事实证明,每当您在表达式中使用类似于我的示例中的数组时,它都会“衰减”为指向第一个元素的指针。所以我们实际上无法按值将数组传递给函数,因为 C 语言会在行之间将其更改为指向第一个元素的指针。

您可以尝试使用以下代码:

#include <stdio.h>
#include <string.h>

void analyse_inst(char* mnemonic, char* operands);

int main()
{
    char mnemonic[] = "add";
    char operands[] = "five to two";

    analyse_inst(mnemonic, operands);
    printf("%s\n", mnemonic);
}

void analyse_inst(char* mnemonic, char* operands)
{
    printf("%s ", mnemonic);
    printf("%s\n", operands);

    strcpy(mnemonic, "hi");
}

关于c - 如何理解指针 (*) 和寻址 (&) 运算符的概念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54904740/

相关文章:

c - 为什么我无法生成超过 1 个随机字符串?

c - Node->next!=NULL 和 Node!=NULL 在 C 中的区别

c - gcc:如何避免对程序集中定义的函数发出 "used but never defined"警告

c - math.h ceil 在 C 中没有按预期工作

python - 如何将 PyObject* 指针设置为 None?

C++ 链表在函数之间丢失数据

c - Malloc 数组,未初始化值的条件跳转

iphone - 在 objective-c 中保留按值传递的变量是否可以?

f# - 当第 3 方库想要 byref 作为输出参数时,c# 到 f#

C中按值调用