简体   繁体   中英

How to assign a struct member array using a struct pointer?

How to assign an array wrapped into a struct using the struct pointer?

I know this syntax:

size_t initArrayList[] = {1,1,1};
memcpy(pStruct->sizet, initArrayList, sizeof(pStruct->sizet));

is it possible to use a similar syntax as:

Stru = (struct myStruct) {.sizet = {1,1,1}};

using pointers?

I'd appreciate a detailed explanation of what (struct myStruct) {.sizet = {1,1,1}} does.

struct myStruct {
  size_t sizet[3];
} ;

void struInit(struct myStruct * pStruct) ;

int main()
{
struct myStruct Stru;

    struInit(&Stru);

          if (Stru.sizet[1]==1)
              printf("\nStru.sizet[1]==1");

    return 0;
}

void struInit(struct myStruct * pStruct ) {

// I know this syntax
//   size_t initArrayList[] = {1,1,1};
//   memcpy(pStruct->sizet, initArrayList, sizeof(pStruct->sizet));

}

Either calling memcpy using a temporary array (just as commented out in your struInit function)

memcpy(pStruct->sizet, initArrayList, sizeof(pStruct->sizet));

or assigning to the pointed-to structure using a compound literal (notice the use of the * dereference operator)

*pStruct = (struct myStruct){.sizet={1,1,1}};

or even a conventional for -loop, copying element by element, does what you want.

Or if you can not rely on designated initializers or compound literals, both being features that have only been standardized since C99, you can use an equivalent, C89 way, that doesn't make use of them:

struct myStruct tmp = {{1,1,1}};
*pStruct = tmp;

I'd appreciate a detailed explanation of what (struct myStruct) {.sizet = {1,1,1}} does.

The relevant parts of C99 describing designated initializers and compound literals are 6.7.8 Initialization and 6.5.2.5 Compound literals .

The short answer is that if used in the struInit function it constructs a local unnamed object with the type struct myStruct , initializing its member sizet to {1,1,1} , this in turn being syntax for array element initialization, assigning a value of 1 to its elements [0] , [1] , and [2] , in that exact order.

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