使用void子函数更改main中的值

xen*_*n20 1 c pointers void

我遇到了这个问题:

#include <stdio.h>
void change_number(int *x);

int main()
{
   int x;
   printf("Enter the number x: ")
   scanf("%d", &x);
   printf("In the main program: x = %d\n", x);
   change_number(&x);
   printf("In the main program: x = %d\n", x);
   return 0;
}
void change_number(int *x)
{
   x = *x+3;
   printf("In the subroutine: x = %d\n", x);
}
Run Code Online (Sandbox Code Playgroud)

预期产量:

Enter the number x: 555
In the main program: x = 555
In the subroutine: x = 558
In the main program: x = 558
Run Code Online (Sandbox Code Playgroud)

两个笔记:

  1. 我无法修改main或之前的任何内容.我只能修改void change_number函数,里面的代码是我自己的代码.

  2. 我无法获得所需的输出 - 我的代码只x+3在子程序中输出,但不会在主程序中更改它.

我如何改变主程序中的值?请记住,我是C的新手,并且还不知道很多东西(事实上,我昨天刚刚介绍了指针).

Ed *_*eal 5

代码

void change_number(int *x)
{
   x = *x+3;
   printf("In the subroutine: x = %d\n", x);
}
Run Code Online (Sandbox Code Playgroud)

应该读

void change_number(int *x)
{
   *x = *x+3;
   printf("In the subroutine: *x = %d\n", *x);
}
Run Code Online (Sandbox Code Playgroud)

这将按预期使用指针(您还需要在LHS上取消引用它们)


Pao*_*olo 5

我认为 OP 问题的答案需要一些解释,因为 C 语法有时可能会令人困惑:

该函数声明为

void change_number(int *x)
Run Code Online (Sandbox Code Playgroud)

*意味着输入参数x是一个指向 int 类型变量的指针。换句话说,x代表内存中的一个位置。


函数内部:

xint值在内存中的地址

*x 是指向的内存地址的“内容” x

因此,正如其他人正确指出的那样,该函数应写为

void change_number(int *x)
{
   *x = *x+3;
   printf("In the subroutine: x = %d\n", *x);
}
Run Code Online (Sandbox Code Playgroud)

因为当你采取行动时,*x你正在采取行动x


发生了main()什么?

x是一个int变量。

你打电话给:

change_number(&x);
Run Code Online (Sandbox Code Playgroud)

amplers&表示您没有传递 的值x

相反,您将指针传递给x,换句话说,x就是存储内容的内存中的地址。

换句话说x,通过引用传递。


最后一点:当用c编写程序时(好吧,用任何语言,但特别是用 c),编译器警告/错误和调试器是你最好的朋友。

此外,一个好的IDE会在您键入代码时向您显示警告。

无论如何......编译器应该警告你

x = *x+3;
Run Code Online (Sandbox Code Playgroud)

涉及从intto int *(指向 int 的指针)的隐式转换,并且很可能是一个错误。