从 C 函数的指针参数获取值

发布于 2024-12-11 11:35:59 字数 366 浏览 0 评论 0原文

当我开始在大学学习时,我们正在学习如何用 C 语言编写,我们已经了解到我可以使用指针作为函数参数,但他们没有告诉我们如何从中获取值它。作为一个对 C 不太了解的人,除了使用两个参数(一个作为指向变量的指针,另一个作为值)之外,我无法想出其他解决方案。请参阅示例,它不是真正的代码,但它只是出于演示目的:


int main(int argc, char* argv []) {

     int a;
     addNumber(&a);


}

void addNumber(int * a) {
     *a = *a + 1; // this obviously does not work
}


任何意见将不胜感激。 谢谢!

as I am starting to study at university we are learning how to write in C and we got to the point where I've learned that I can use pointers as function parameters but what they haven't told us is how to get the value from it. I am not able as a person who doesn't know about C as much, to come up with other solution than use two parameters (one as pointer to the variable and other as value. See the example which is not real code but it's just for purpose of demonstration:


int main(int argc, char* argv []) {

     int a;
     addNumber(&a);


}

void addNumber(int * a) {
     *a = *a + 1; // this obviously does not work
}


Any input would be appreciated.
Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

迷你仙 2024-12-18 11:35:59

只有一件大事:您忘记初始化 a。否则,看起来不错。

 int a = 0;
 addNumber(&a);

唯一的另一件事是您缺少 main 中的 return 语句。

Only one major thing: You forgot to initialize a. Otherwise, it looks fine.

 int a = 0;
 addNumber(&a);

The only other thing is that you're missing the return statement in main.

绳情 2024-12-18 11:35:59

这是一个可能更接近您正在寻找的示例:

#include <stdio.h>

void increment(int *a, int *b)
{
    *a = *a + *b;
}

int main(void)
{
    int sum = 5;
    int increment_by = 7;
    printf("sum: %d, increment_by: %d\n", sum, increment_by);
    increment(&sum, &increment_by);
    printf("sum: %d, increment_by: %d\n", sum, increment_by);

    return 0;
}

输出:

$ ./bar
sum: 5, increment_by: 7
sum: 12, increment_by: 7

Here is an example that may be closer to what you are looking for:

#include <stdio.h>

void increment(int *a, int *b)
{
    *a = *a + *b;
}

int main(void)
{
    int sum = 5;
    int increment_by = 7;
    printf("sum: %d, increment_by: %d\n", sum, increment_by);
    increment(&sum, &increment_by);
    printf("sum: %d, increment_by: %d\n", sum, increment_by);

    return 0;
}

output:

$ ./bar
sum: 5, increment_by: 7
sum: 12, increment_by: 7
素染倾城色 2024-12-18 11:35:59

它会起作用的。如果将 a 初始化为某个值,效果会更好。

It will work. It will work better if you initialise a, to some value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文