Justin S.
Justin S.

Reputation: 25

How to change the value of data inside a struct through a function?

first time posting here, any help would be appreciated. I'm trying to change the value "size" inside my stack called "try", by putting it through my function called Stack_Init. If I print out the value of "stack->size" inside the function, it gives me the correct value for size (being 4). If I were to print try->size after executing my function (at the end of the code), it would give me a value of 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);

Thanks for reading!

Upvotes: 2

Views: 77

Answers (2)

kamoroso94
kamoroso94

Reputation: 1735

Your Stack_Init function has a couple problems with it. You are modifying a local variable instead of the argument passed to the function, and you're assigning the memory incorrectly. Try this instead.

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You are trying to change a pointer that you pass to the function, so you need an extra level of indirection, i.e. a pointer to pointer. In addition, you need to assign to dereferenced parameter instead of a local variable:

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;
}

The call to the function needs to look like this:

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

Upvotes: 3

Related Questions