如何通过函数更改结构中的数据值?

时间:2016-07-27 02:58:04

标签: c

第一次发布在这里,任何帮助将不胜感激。我试图通过我的函数Stack_Init来改变我的堆栈中名为“try”的值“size”。如果我在函数内打印出“stack-> size”的值,它会给出正确的大小值(为4)。如果我要打印 执行我的函数后try->size(在代码的末尾),它会给我一个值0.

struct intnode {
    int data;
    struct intnode *next; 
}; typedef struct intnode node; 

struct stack {
    node *top;     
    int size;
}; typedef struct stack Stack;

void Stack_Init(Stack *S, int size){
    Stack *stack = malloc(size*sizeof(node)); 
    stack->top = NULL;
    stack->size = size;//for some reason, this doesn't change try->size
}
int main(){
    Stack *try;
    int size = 4;
    Stack_Init(try,size);
    printf("%d %d ", try->size, try->top);

感谢阅读!

2 个答案:

答案 0 :(得分:3)

您正在尝试更改传递给函数的指针,因此您需要额外的间接级别,即指向指针的指针。此外,您需要分配取消引用的参数而不是局部变量:

void Stack_Init(Stack **S, int size){
    //                 ^
    //                 |
    //        Extra asterisk here
    *S = malloc(size*sizeof(node)); 
//  ^
//  |
// Dereference the pointer passed into the function
    (*S)->top = NULL;
    (*S)->size = size;
}

对函数的调用需要如下所示:

Stack_Init(&try,size);
//         ^
//         |
// Pass a pointer to a pointer

答案 1 :(得分:0)

您的Stack_Init功能有两个问题。您正在修改局部变量而不是传递给函数的参数,并且您正在错误地分配内存。试试这个。

void Stack_Init(Stack **S,int size) {
    Stack *stack = (Stack*)malloc(sizeof(Stack));
    stack->top = NULL;
    stack->size = size;
    *S = stack;
}