Multidimensional array as a structure member memory allocation C -


i started learn c 10 days ago , decided write battleship game. have structure player has 2d integer array member.

   struct player{    ...    int field[x][y];...}; 

x , y both 5 in case.

when create new player in main , call print_field(int field[x][y]) method (that prints members of field)

int main(){    struct player player1;    print_field(player1.field);} 

i random stuff like
00000 18356276361600061541186983333419528026550 00010 41963970000 04196320041956320

i tried different obvious ways of malloc , calloc like

player1.field = malloc(sizeof(player1.field)); 

but different types of pointers, array or cast exceptions.

please explain me how works.

when define local (non-static) variable, or allocate memory through malloc, memory not initialized in way. content indeterminate , seemingly random (in reality whatever happens in memory @ time).

using memory in way, except initialize it, leads undefined behavior.

you can initialize whole structure when define variable:

struct player player1 = { ..., { { 0 } } }; 

also note that

player1.field = malloc(sizeof(player1.field)); 

is wrong. compiler should have complained it. can't assign array. , don't need allocate memory either. compiler make sure memory whole structure allocated when define player1 variable.


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -