将地址传递给 C 中的函数 [英] Passing addresses to functions in C

查看:56
本文介绍了将地址传递给 C 中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C 的新手,我有一个计算几个变量的函数.但是现在让我们简化一下.我想要的是有一个返回"多个变量的函数.虽然据我所知,你只能在 C 中返回一个变量.所以我被告知你可以传递一个变量的地址并这样做.这是我走了多远,我想知道我能伸出援手.我在 C90 禁止的东西等方面遇到了相当多的错误.我几乎肯定这是我的语法.

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.

说这是我的主要功能:

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?

推荐答案

你应该使用 *variable 来引用指针所指向的内容:

You should use *variable to refer to what a pointer points to:

*x = 5;
*y = 5;

您目前正在做的是将指针设置为地址 5.您可能会使用蹩脚的旧编译器,但是好的编译器会在将 int 分配给 时检测到类型不匹配>int* 变量,如果没有显式转换,您将无法执行此操作.

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 an int* variable and will not let you do it without an explicit cast.

这篇关于将地址传递给 C 中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆