将值传递给函数参数中的void指针

时间:2020-03-25 09:52:00

标签: c

我有小问题。

如何将值转换为空指针:

void foo (void *arg){
    int test = *(int *)arg;
}

void main(){
    foo(&5);    <- ????
}

致谢

1 个答案:

答案 0 :(得分:-1)

取决于您的真实意思。以下一些选项可能为您提供一些启发:

void foo (void *arg){
    int test = *(int *)arg;
}

void main(){
    int val = 5

    // Pass the variable address in
    foo(&val);

    // See what's add memory address 0x5
    foo((void*)5);

    fooPtr(&val); // val is incremented
    fooByValue(val); // val is unchanged
}

void fooIntPtr(int *ptr){
    (*ptr)++;
}

void fooByValue(int test){
    // same effect as your "foo" but safe and quicker
    test++;
}

(对于学习C ++的任何人,您也可以通过引用来传递:void fooRef(int &val)