I am dealing with an issue about multidimensional char
array in C. After a time break it is hard for me for remembering the all. Try to figure out what I am doing the wrong. Platform is Ubuntu 21.10, compiler is gcc, the code is below. Any help
I would be much appreciated.
#include <stdio.h>
int main() {
char *a1 = "hello1";
char *a2 = "hello2";
char b[][2] = { a1, a2 };
printf("%sn", b[1]);
getchar();
return (0);
}
5
Answers
It's me again
Thanks for assist
Because
a1
anda2
are pointers, you need an array of pointers to contain them:So what you need isn’t really an array of arrays, but just a standard single one-dimensional array.
Also note that I added the
const
modifier, to make it an array of pointers to constant characters. That’s because it’s not allowed to modify literal strings, so all pointers to them should be made constant.If you really want an array of arrays, for example so you would be able modify the strings, you first of all need to make sure that the dimensions are correct. You have two strings, so you need an array of two elements. Then you need the second "dimension" to be large enough to hold both the strings and all possible additions you might need to do.
For example:
But note that you can’t initialize these arrays using the pointers you have, or even using other arrays. Instead you must explicitly copy the strings into the arrays:
Correction is
Corrected code
Array of pointer is not a 2D array.
This defines and initializes 2D
char
array:also a way: