简体   繁体   中英

How to store a memory address of a 2d array in a pointer member of a struct in C

The struct is

struct cloud {
    //declare a pointer to point to the 2d array
    char *pointer;

};

The main function is given (struct cloud u*) as a parameter, in order to refer to the structure

The rest of the function involves assigning the values to a 2d array arr, then I need to make the pointer in the struct point to the memory location of the 2d array.

So far I've done the following and the memory address of the struct pointer does not change after the assignment.

    printf("2d array memory address is %p\n", arr);
    printf("struct array memory address before assignment is %p\n", &(u->pointer));

    u->pointer = arr;

    printf("struct array memory address after assignment is %p\n", &(u->pointer));

As you wrote in the comment you have a one-dimensional array declared like

char *arr[rownum];

Within the structure you can declare a pointer that will point to the first element of the array like

struct cloud {
    char **pointer;
};

and then write something like

u->pointer = arr;

Pay attention to that if the array is a local variable of a function and an object of the structure is declared outside the function then after exiting the function the pointer will have an invalid value because the array will not be alive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM