简体   繁体   中英

Initialize a 2d array inside a struct

I am trying to initialize a 2d array of ints inside a struct. In the beginning of my program (global access) I have created a struct, and an array of this struct:

struct block {
   int theblock[3][3];
};

struct block blockArray[6];

Then I am trying to initialize the array of structs in a function:

void afunction() {
    int block1[3][3] = {
        {0, 1, 0},
        {0, 1, 0},
        {0, 1, 0}
    };

    blockArray[0].theblock = block1;   
}

Compiler error:

error: incompatible types when assigning to type 'int[3][3]' from type 'int[*][3]'

Could anyone please explain what I have done wrong here, I know this is pretty basic stuff but I have really tried to read up and solve this on my own. I am coming from Java and trying to learn C.

Create a temporary struct and assign it to your element of the array of structs:

struct block temp = { { {0, 1, 0}, {0, 1, 0}, {0, 1, 0} } } ;

blockArray[0] = temp ; 

or just use your array and copy it:

int temp[3][3] = { {0, 1, 0}, {0, 1, 0}, {0, 1, 0} } ;

assert( sizeof( temp ) == sizeof( blockArray[0].theblock ) ) ;
memcpy( blockArray[0].theblock , temp , sizeof( temp ) ) ; 

You can not copy an array this way in C. For that matter, I didn't think you could do it in Java either.

You can copy the pointers around, for instance

blockArray[0].theblock = block1;

But all this will do is to have blockArray[0].theblock point at the same address as &block1[0]. It does not copy any content, it's a shallow copy.

You'll have to copy the members over with memcpy() or in loop(s):

for (int i = 0; i < 3; i++)
    for (int j = 0; j < 3; j++)
        blockarray[0].theblock[i][j] = block1[i][j];

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