Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected pointer to struct behavior

#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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading