c - Assigning 2-dimensional array to struct object -


i have 2-dimensional array. want array assigned struct. please take look:

this struct:

typedef struct {     int x;     int y;     char **table; //2-dim array } some_struct; 

and want able assign this:

const char sth1_table[2][3] = {    { ' ', 'x', ' '},    { 'x', 'x', 'x'}, }; 

or this:

const char sth2_table[4][2] = {    { 'x', ' '},    { 'x', ' '},    { 'x', ' '},    { 'x', 'x'}, }; 

to struct.

how that? tried assigning:

new_sth.table = malloc(sizeof(sth1_table)); *new_sth.table = sth1_table; 

and accessing:

some_struct get_sth; get_sth = *(some_struct+i); other_array[a][b] = get_sth.table[a][b]; 

but no luck.

what doing wrong?

for starters member table not 2 dimensional array. pointer.

arrays not have assignment operator. have copy arrays element element.

for example if have object of structure

typedef struct {     int x;     int y;     char **table; // pointer } some_struct;  some_struct obj; 

and array

const char sth1_table[2][3] = {    { ' ', 'x', ' '},    { 'x', 'x', 'x'}, }; 

then can make following way

obj.table = malloc( sizeof( char *[2] ) );  ( size_t = 0; < 2; i++ ) {     obj.table[i] = malloc( sizeof( sth1_table[i] ) );     memcpy( obj.table[i], sth1_table[i], sizeof( sth1_table[i] ) ); }  

you should remember have free allocated memory or realloc when need use two-dimensional array initializer.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -