C语言 函数中的指针设置不正确

toe95027  于 2023-01-29  发布在  其他
关注(0)|答案(1)|浏览(118)

我有一个代码,我用指针
其中一个函数位于文件1中
在主文件中调用文件1的函数
当我传递指针时它没有被定义,
我收到测试为空消息
正确的使用方法是什么?
我的代码:

    • 文件1**
struct mystruct {
    unsigned short id;
    int number;
    ....
}

struct mystruct *test_check(state *ck, char *name);

void GetMytest(state *ck, char *name, struct mystruct *test) {
        checkfield(ck, name);
        test = test_check(ck, name);
        .....
}
    • 主文件**
struct mystruct *test

void MainTest() {

    state *ck = check_new();
    .....

    GetMytest(ck, "Stats", test);
    
    if(test == NULL)
        printf("Test is NULL");

}
wpcxdonn

wpcxdonn1#

GetMytest中的语句test = test_check(ck, name);只修改局部参数变量test,而不是同名的全局变量。
如果你想在调用作用域(MainTest函数或全局作用域)中更新指针,你必须传递一个指向这个变量的指针。
我在我的一些代码中做了类似的事情
请尝试以下操作

文件1:

void GetMytest(state *ck, char *name, struct mystruct **test) {
        checkfield(ck, name);
        *test = test_check(ck, name);
        .....
}

主要功能:

void MainTest() {

    state *ck = check_new();
    .....

    GetMytest(ck, "Stats", &test);
    
    if (test == NULL)
        printf("Test is NULL");
}

如果其他功能正常,则应能解决问题。

相关问题