调用函数时如何使用指针 [英] How to use pointers when calling a function

查看:246
本文介绍了调用函数时如何使用指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用C语言编程时遇到了一些问题.我有一个类似

I have some issue with programming in C. I have a structrure, that goes like

 typedef struct Hash_Funct{
char* name;             
Var_Table * List_of_Variables;   ///pointer to list of variables
} Hash_Funct;

在某些代码点上,我想通过以下方式初始化结构:

And in certain point of code, I want to inicialize the structure with:

    Hash_Funct tmp = (Hash_Funct*) malloc(sizeof(Hash_Funct));
    tmp->name=name;
    Init_ID_Table(tmp->List_of_Variables);

Init_ID_Table();定义为:

Where the Init_ID_Table(); is defined as:

void Init_ID_Table(Var_Table *table){
    table = (Var_Table*) malloc ( sizeof(Var_Table) );
    for(int i=0; i< SIZE;i++){
        (*table)[i] = NULL;
    }
}

但是,在此代码的结尾,Init_ID_Table()似乎对* List_of_Variables指针(现在应该指向大小为SIZE的表并将其所有元素设置为NULL)没有任何影响.有人至少可以告诉我发生了什么事,如果没有怎么做就可以按预期工作呢?

However, at the end of this code, it doesnt seems that the Init_ID_Table() had any affect on the * List_of_Variables pointer (which should now point onto a table of size SIZE and have all its elements set to NULL). Can anyone at least tell me what is going on if not how to change it to work as expected?

非常感谢你, 亚当

推荐答案

变量按值传递,在函数中分配给参数变量对调用者的变量没有影响.

Variables are passed by value, assigning to the parameter variable in the function has no effect on the caller's variable.

您需要将指针传递给struct成员,并间接通过它来修改调用方的变量.

You need to pass a pointer to the struct member, and indirect through it to modify the caller's variable.

void Init_ID_Table(Var_Table **table) {
    Var_Table *temp_table = malloc ( sizeof(Var_Table) );
    for (int i = 0; i < SIZE; i++) {
        temp_table[i] = NULL;
    }
    *table = temp_table;
}

然后您将这样称呼:

Init_ID_Table(&(tmp->List_Of_Variables));

这篇关于调用函数时如何使用指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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