指针参数在另一个函数内的函数?

时间:2022-07-06 16:04:35

I'm very new to C (and coding in general) so I apologize if this is a stupid question. What I have is a function that takes an integer pointer as one of it's arguments, and i'm trying to call it from inside another function.

我对C(和一般编码)很新,所以如果这是一个愚蠢的问题,我道歉。我所拥有的是一个函数,它将一个整数指针作为其中一个参数,我试图从另一个函数内部调用它。

for example:

int a;

void function1(int* a)
{
/* Code */
}

void function2(int* a)
{
   function1(&a);
}

I don't know how to call the function or if this is even the proper way to do this. Basically I need function 1 to be able to change the value of "a" in main when it is called in function 2. Thanks :)

我不知道如何调用该函数或者这是否是正确的方法。基本上我需要函数1能够在函数2中调用main时更改“a”的值。谢谢:)

1 个解决方案

#1


1  

The parameter 'a' of function2 is already a pointer, so you should pass 'a', not '&a', to function1 within function2. What you are doing now is passing the address of the element storing the pointer, rather than the pointer itself. When you call function2 in your main() code, however, you should pass '&a' to it.

function2的参数'a'已经是一个指针,因此你应该将'a'而不是'&a'传递给function2中的function1。你现在正在做的是传递存储指针的元素的地址,而不是指针本身。但是,当您在main()代码中调用function2时,应该将'&a'传递给它。

#1


1  

The parameter 'a' of function2 is already a pointer, so you should pass 'a', not '&a', to function1 within function2. What you are doing now is passing the address of the element storing the pointer, rather than the pointer itself. When you call function2 in your main() code, however, you should pass '&a' to it.

function2的参数'a'已经是一个指针,因此你应该将'a'而不是'&a'传递给function2中的function1。你现在正在做的是传递存储指针的元素的地址,而不是指针本身。但是,当您在main()代码中调用function2时,应该将'&a'传递给它。