Home > Net >  Unexpected pointer to struct behavior
Unexpected pointer to struct behavior

Time:06-30

#include <stdio.h>

struct arr_wrapper{
    int* arr;
};

struct bar{
    struct arr_wrapper* arr_wrapper_obj;
};

void assign_arr(struct arr_wrapper* X){
    int arr[3];
    for (int i = 0; i < 3; i  ){
        arr[i] = i;
    }
    X->arr = arr;
    return;
}

void my_func(struct bar* bar_obj){
    for (int i = 0; i < 3; i  ){
        printf("%d\n", bar_obj->arr_wrapper_obj->arr[i]);
    }
    return;
}

int main()
{
    struct arr_wrapper arr_wrapper_obj;

    assign_arr(&arr_wrapper_obj);
    for (int i = 0; i < 3; i  ){
        printf("%d\n", arr_wrapper_obj.arr[i]);
    }
    struct bar bar_obj;
    bar_obj.arr_wrapper_obj = &arr_wrapper_obj;
    for (int i = 0; i < 3; i  ){
        printf("%d\n", bar_obj.arr_wrapper_obj->arr[i]);
    }
    my_func(&bar_obj);
    printf("Hello World");

    return 0;
}

Output of this line of code is:

0
1
2
0
1
2
32765
1
2
Hello World

This is a simplified version of my code.

I'm trying to create an structure of structure, the inner structure has an array.

However, the size of the array is dynamic and cannot be determined before run time, so I used a int pointer to point to the array. My question is: why the 7th line has this strange value instead of 0.

CodePudding user response:

You are saving the address of a local variable.

void assign_arr(struct arr_wrapper* X){
    int arr[3]; // <<<<=== local variable
    for (int i = 0; i < 3; i  ){
        arr[i] = i;
    }
    X->arr = arr; <<<<, save it
    return;
}

This is invalid. The locals are released once the function returns.

  • Related