C returning answer through parameters ( refernce)

倖福魔咒の 提交于 2019-12-23 04:45:09

问题


Hy everyone,

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 \n", (*helo));
    getchar();
    return 0;
}

回答1:


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\n", 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 \n", (*helo));
    getchar();
    return 0;
}

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).




回答2:


can you try printf("Value: %d \n", (*helo)); instead of printf("Value: %s \n", (*helo));?




回答3:


c is pass by value. When you pass a parameter to a function, a copy of it is made. You need to receive as pointer to pointer to achieve C++ feature of pass by reference.

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

And at the call it as -

setup(&helo) ;


来源:https://stackoverflow.com/questions/7917840/c-returning-answer-through-parameters-refernce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!