Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String initialization in multidimensional array

How to assign string value in multidimensional array, send the array as a function argument, and return it back to main function? I tried this but it gives an error:

char a[250][250][250];   // does not work
a[][0][2] = "0";         // does not work
a[][1][2] = "0";         // does not work

char a[][2][2] = {"0", "1"};  // works

// error: expected primary-expression before ']' token
a[i][j][max] = add_func(a[i][j][], i, j); 
like image 303
sabbir Avatar asked Dec 08 '22 18:12

sabbir


1 Answers

After declaration you can not assign, but use strcpy()

char a[250][250][250];

strcpy(a[0][1],"0");

or assign at the time of declaration:

char a[250][250][250] = {"0","2"};  
char a[][250][250] = {"0","2"}; 

or if you want to assign a single char.

a[i][j][k] = '0'; 

Where i, j, k are any value less than 250


How to Declaration and Initialization 3D Array IN C

In-general a[3][4][2] is a three-dimension array, that can be view as

a[3][4][2] : Consist of 3 two-dimension arrays, where each 2-D array are consist of 4-rows and 2-colunms. can be declare as:

char a[3][4][2] =  { 
                       { //oth 2-D array 
                         {"0"},
                         {"1"},
                         {"2"},
                         {"4"}
                       },
                       { //1th 2-D Array
                         {"0"},
                         {"1"},
                         {"2"},
                         {"4"}
                       },
                       { //2nd 2-D array
                         {"0"},
                         {"1"},
                         {"2"},
                         {"4"}
                       },
                   };  

Note: "1" means two chars, one additional fro null ('\0') char.

If integer array:

int a[3][2][3]=  
        {
            { //oth 2-D array, consists of 2-rows and 3-cols
            {11, 12, 13},
            {17, 18, 19}
            },
            {//1th 2-D array, consists of 2-rows and 3-cols
            {21, 22, 23},
            {27, 28, 29}
            },
            {//2th 2-D array, consists of 2-rows and 3-cols
            {31, 32, 33},
            {37, 38, 39}
            },
        };

Link to understand


Second error:

to this a[i][j][max] a char can assign not string so,

a[i][j][max] = '0' ; // is correct  expression 

but

a[i][j][max] = "0";  // is not correct, wrong   

Please read WhozCraig comment. you are declaring huge memory in stack!


According to your comment :

function declaration:

char add_func(char a[250][250][250], int i, int j); // function definition  

try like this:

  char a[250][250][250];
  a[i][j][max] = add_func(a, i, j );
like image 61
Grijesh Chauhan Avatar answered Dec 20 '22 19:12

Grijesh Chauhan