I have a two-dimensional char
array (an array of strings). When I try to assign a string to an element, an error occurs saying "array type 'char *[8]' is not assignable".
This is my code:
int main() {
char *array[4][8];
array[0] = "test";
}
How would I properly assign an element of a 2-D array?
CodePudding user response:
Maybe by using 2 dimensions of the 2D array. array[0][0] = "test;"
Though please note that in your case this is a 2D array of pointers to string literals. And since string literals are read-only, it should be declared as const char *array[4][8];
. If you want read/write memory then you should assign the pointers to dynamically allocated memory instead.
CodePudding user response:
the error is may be beacuse you trspecifing row and not column of the array(remeber you are using 2D array).
Try this:
int main() {
char *array[4][8];
array[0][0] = "test";
}
CodePudding user response:
int main() {
char *array[4][8];
array[0] = "test";
}
In the above code you first create a two-dimensional array of char*
. The mistake occures on the second line. You are trying to assign a value to array[0]
, but since array is a two dimensional array array[0]
doesn't point to a char*
, instead it points to an array of char*
. The correct way of doing this would be:
array[0][0] = "test";
This would assign the first element in the first array to "test".
CodePudding user response:
I have a two-dimensional char array (an array of strings).
This is my code:
char *array[4][8];
That is not a two-dimensinal char array. It's a two-dimentional array of char pointers.
To get a two-dimentional char array that can be used as an array of strings do
char array[4][8]; // i.e. without *
Now you can save 4 strings with max length 7.
C has no way to assign a string using =
. In C you can use strcpy
to copy a string into your variable like:
strcpy(array[0], "test");
However, you can initialize the array with strings using =
like:
char array[4][8] ={"test", "hello", "world", "done"};
and for instance print them like:
for (int i=0; i < 4; i) puts(array[i]);
The output will be:
test
hello
world
done
The second dimension of the array can be used to access the individual characters of the strings. For instance:
printf("%c", array[1][4]);
will print the o
from hello
CodePudding user response:
You need to use the correct array subscript. The type of array[0]
is char *[8]
but you need array[0][0]
which is of type char *
. Then you want to allocate a writable string with for example strdup()
:
#include <string.h>
// ...
char *array[4][8];
array[0][0] = strdup("test");
free(array[0][0]);
You could also change the type to const
as you cannot change that string literal:
const char *array2[4][8];
array2[0][0] = "test";
Or perhaps you meant to copy the data into an an array:
#include <string.h>
//...
char array3[4][8];
strcpy(array3[0], "test");