将地址传递给 C 中的函数
我是 C 新手,我有一个计算一些变量的函数。但现在让我们简化一下事情。我想要的是有一个“返回”多个变量的函数。虽然据我了解,在 C 中你只能返回一个变量。所以我被告知你可以传递变量的地址并这样做。这就是我所取得的进展,我想知道我是否可以伸出援手。我收到了一些关于 C90 禁止内容等的错误。我几乎肯定这是我的语法。
假设这是我的主要功能:
void func(int*, int*);
int main()
{
int x, y;
func(&x, &y);
printf("Value of x is: %d\n", x);
printf("Value of y is: %d\n", y);
return 0;
}
void func(int* x, int* y)
{
x = 5;
y = 5;
}
这本质上是我正在使用的结构。有人可以帮我吗?
I'm new to C and I have a function that calculates a few variables. But for now let's simplify things. What I want is to have a function that "returns" multiple variables. Though as I understand it, you can only return one variable in C. So I was told you can pass the address of a variable and do it that way. This is how far I got and I was wondering I could have a hand. I'm getting a fair bit of errors regarding C90 forbidden stuff etc. I'm almost positive it's my syntax.
Say this is my main function:
void func(int*, int*);
int main()
{
int x, y;
func(&x, &y);
printf("Value of x is: %d\n", x);
printf("Value of y is: %d\n", y);
return 0;
}
void func(int* x, int* y)
{
x = 5;
y = 5;
}
This is essentially the structure that I'm working with. Could anyone give me a hand here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该使用 *variable 来引用指针所指向的内容:
您当前正在做的是将指针设置为地址 5。您可能会使用蹩脚的旧编译器,但一个好的编译器会检测到将
int
分配给int*
变量时存在类型不匹配,并且在没有显式强制转换的情况下不允许您执行此操作。You should use
*variable
to refer to what a pointer points to:What you are currently doing is to set the pointer to address 5. You may get away with crappy old compilers, but a good compiler will detect a type mismatch in assigning an
int
to anint*
variable and will not let you do it without an explicit cast.会改变参数的值。
would change the values of the parameters.
除了其他发帖者建议的函数体更改之外,请将您的原型更改为
void func(int *,int *)
,并更改您的函数定义(在 main 下方)以将 void 反映为出色地。当您不指定返回类型时,编译器会认为您试图暗示 int 返回。In addition to the changes that the other posters have suggested for your function body, change your prototype to
void func(int *,int *)
, and change your function definition (beneath main) to reflect void as well. When you don't specify a return type, the compiler thinks you are trying to imply an int return.当实际上是 func(int*, int*) 时,您不能转发声明 func(int,int) 。此外,func 的返回类型应该是什么?由于它不使用 return,我建议使用 void func(int*, int*)。
You can't forward declare func(int,int) when in reality it is func(int*, int*). Moreover, what should the return type of func be? Since it doesn't use return, I'd suggest using void func(int*, int*).
您可以返回结构类型的单个变量。
You can return a single variable of a struct type.