C 通过参数返回答案(参考) [英] C returning answer through parameters ( refernce)

查看:30
本文介绍了C 通过参数返回答案(参考)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

请考虑这个小代码,并帮助我弄清楚为什么它不起作用?

pls consider this small code, and help me to figure out, why it's not working?

#include <stdio.h>
#include <stdlib.h>

void setup(int* helo) {
    helo = (int*) malloc(sizeof(int));
    (*helo) = 8;
}

int main(int argc, char* argv[]) {
    int* helo = NULL;
    setup(helo);
    printf("Value: %s 
", (*helo));
    getchar();
    return 0;
}

推荐答案

您正在此处寻找两种选择之一.您可以从等式中取出内存指针分配,并传递标准变量的内存地址:

You are looking for one of two options here. You can either take the memory pointer allocation out of the equation, and pass the memory address of a standard variable:

void setup(int* helo) 
{
    *helo = 8;
}

int main(int argc, char* argv[]) {
    int helo = 0;
    setup(helo);
    printf("Value: %d
", helo);
    getchar();
    return 0;
}

或者,如果您想坚持自己的方法,函数的签名需要更改以接收指向指针的指针:

Or, if you want to stick with your approach, the signature of your function needs to change to receive a pointer to a pointer:

void setup(int** helo) {
    *helo = (int*) malloc(sizeof(int));
    *(*helo) = 8;
}

int main(int argc, char* argv[]) {
    int* helo = NULL;
    setup(&helo);
    printf("Value: %d 
", (*helo));
    getchar();
    return 0;
}

这样做的原因是setup(int* helo) 接收main()中声明的int* helo的副本),并且这个本地副本将指向同一个地方.因此,无论您在 setup() 内使用 helo 做什么,都将更改变量的本地副本,而不是 helo来自 main().这就是为什么您需要将签名更改为 setup(int** helo).

The reason for this is that setup(int* helo) receives a copy of int* helo declared in main(), and this local copy will point to the same place. So whatever you do with helo inside setup() will be changing the local copy of the variable and not helo from main(). That's why you need to change the signature to setup(int** helo).

这篇关于C 通过参数返回答案(参考)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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