简体   繁体   中英

typedef, arrays and pointers in C

I am studying a code written in C language.

The following part isn't clear for me:

typedef uint8_t data_t[4][4];

typedef struct {
   data_t *data;
   ...
} my_struct;

The thing that I don't understand is, what is the type of data ?

Plus, I want to assign values to this variable. For example, in the code there is:

my_struct st;
st.data = (int8_t *)array

where array is defined as int8_t *array .

I don't understand how this assignation works, could someone explain it clearly?

To finish, is it possible to assign values to my data_t variable without declaring it as a pointer in my structure?

The thing that I don't understand is, what is the type of data?

The type of data is a pointer to a two-dimensional array. That is uint8_t(*data)[4][4] .

See C right-left rule for deciphering C declarations.

Plus, I want to assign values to this variable st.data = (int8_t *)array .

In this case array must have the same layout as uint8_t[4][4] array. Since arrays are contiguous in C , that array must have at least 4 * 4 elements of type int8_t .

The fact that you have to cast the array with (uint8_t*) first implies that array has a different type and that may cause trouble.

Note that this is a pointer assignment only, not an element-wise copy of array .

is it possible to assign values to my data_t variable without declaring it as a pointer in my structure?

It is possible if data is not a pointer, ie declare it as data_t data; . And then copy into it using memcpy .

This declaration

typedef uint8_t data_t[4][4];

declares name data_t as an alias for type uint8_t [4][4] .

Thus in the structure definition

typedef struct {
   data_t *data;
   ...
} my_struct;

member data is a pointer of type data_t * that is the same as uint8_t ( * )[4][4] .

So it is a pointer to a two-dimensional array of pointers to objects of type `uint8_t

Arrays do not have the assignment operator. You have to copy elements of one array into another.

If for example you have another one-dimensional array of pointers like

uint8_t *array[4];

you could write

my_struct st;
st.data = malloc( sizeof( data_t ) );
memcpy( st.( *data )[0], array, 4 * sizeof( uint8_t * ) );

Take into account that as the data is a pointer you have at first to allocate memory where you are going to copy objects of type uint8_t * .

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