C帮助-具有两个值的同一变量
我有一个带有输入变量的函数,它被这个函数修改(我可以测试,最后的变量是正确的),这个函数在file1.c中,在file1.h中声明,我通过主文件(main.c)调用了这个函数。但是当我在main.c中使用这个函数时,变量不会被修改 为了更容易理解,举个例子: 在file1.c->C帮助-具有两个值的同一变量,c,C,我有一个带有输入变量的函数,它被这个函数修改(我可以测试,最后的变量是正确的),这个函数在file1.c中,在file1.h中声明,我通过主文件(main.c)调用了这个函数。但是当我在main.c中使用这个函数时,变量不会被修改 为了更容易理解,举个例子: 在file1.c-> void funcion(char input1[], int input2){ --> Here some modificions happends printf("Variables first are
void funcion(char input1[], int input2){
--> Here some modificions happends
printf("Variables first are %c %d", input1[0], input2);
//the function end after this print
}
void funcion(char input1[], int input2);
#include "file1.h"
main()
{
char *input1;
int input2;
function(input1, input2);
printf("Variables second are %c %d", input1[0], input2);
}
在file1.h->
void funcion(char input1[], int input2){
--> Here some modificions happends
printf("Variables first are %c %d", input1[0], input2);
//the function end after this print
}
void funcion(char input1[], int input2);
#include "file1.h"
main()
{
char *input1;
int input2;
function(input1, input2);
printf("Variables second are %c %d", input1[0], input2);
}
在main.c->
void funcion(char input1[], int input2){
--> Here some modificions happends
printf("Variables first are %c %d", input1[0], input2);
//the function end after this print
}
void funcion(char input1[], int input2);
#include "file1.h"
main()
{
char *input1;
int input2;
function(input1, input2);
printf("Variables second are %c %d", input1[0], input2);
}
程序的输出:
Variables first are A B
Variables second are C D
变量A=/=C和B=/=D。请,有人可以帮忙吗?您编写的函数有这些变量的本地副本,因为您没有使用引用调用。您正在使用按值调用。因此,即使函数修改变量,这些修改也不会对从
main()
传递的变量进行。它们是对变量的本地副本执行的,这些变量的作用域仅限于该方法。请仔细阅读“按值调用”和“按引用调用”之间的差异 printf(“变量首先是%c%d”,input1[0],input2”)代码>永远不会打印“变量首先是A B”。发布真实代码、数据和期望值。如果input1
和input2
都未初始化,您希望看到什么?您尚未为数组input1分配内存。这就是问题之一。这有很多重复的地方,但要点是C通过值传递变量,而不是通过引用传递,如果您想修改函数中的变量并在调用者中反映修改,则需要使用引用传递。搜索例如c仿真按引用传递。感谢anwser,我将搜索“按值调用”和“按引用调用”之间的差异。感谢anwser,我将搜索“按值调用”和“按引用调用”之间的差异。