I am new to C and I am trying to experiment with multi-dimensional arrays. I have the following example where I am trying to initialize a multi-dimensional array:
char matrix[5][10];
matrix[0] = {'0','1','2','3','4','5','6','7','8','9'};
matrix[1] = {'a','b','c','d','e','f','g','h','i','j'};
matrix[2] = {'A','B','C','D','E','F','G','H','I','J'};
matrix[3] = {'9','8','7','6','5','4','3','2','1','0'};
matrix[4] = {'J','I','H','G','F','E','D','C','B','A'};
At first glance it would appear that this type of declaration would be valid since a multi-dimensional array is an array of arrays; however, this example fails to properly compile and I am not entirely certain as to why.
I am aware that I am able to initialize a multi-dimensional array using the following notation:
char matrix2[5][10] =
{
{'0','1','2','3','4','5','6','7','8','9'},
{'a','b','c','d','e','f','g','h','i','j'},
{'A','B','C','D','E','F','G','H','I','J'},
{'9','8','7','6','5','4','3','2','1','0'},
{'J','I','H','G','F','E','D','C','B','A'},
};
However, what if I do not know the contents of the array at declaration time and would like to populate this array with data at a later point. I could initialize each individual element as follows:
matrix[0][0] = '0';
matrix[0][1] = '1';
matrix[0][2] = '2';
etc....
I am wondering if it somehow possible to declare each array using my original approach:
matrix[0] = {'0','1','2','3','4','5','6','7','8','9'};
matrix[1] = {'a','b','c','d','e','f','g','h','i','j'};
etc...
I tried to use strcpy
as follows:
strcpy(matrix[0], "012345678");
strcpy(matrix[1], "abcdefghi");
It appears that this might work if the multi-dimensional array was an array of null-terminated strings, but what would be an equivalent to a multi-dimensional array of integers or other data structures. Any help is appreciated. Thank you.
memcpy
instead ofstrcpy
. – BLUEPIXY