What is the best way to initialize a pointer to a char array as mutable?

Clearly, initializing a char array of type

char* string = "foobar";

will make it unchanged. On the other hand, initializing an array of char type

char string[] = "foobar";

will make it volatile.

What is the best way to make variable initialization of a pointer to a char array?

// member char arrays are immutable
char* arr[] = {"foo", "bar"};
+4
source share
2 answers

Assuming you have C99 functions, complex literals do the trick:

char *arr[] = { (char[]){"foo"}, (char[]){"bar"} };
+3
source

One option is to guess the maximum size of the rows in the array and use:

char arr[][SIZE] = {"foo", "bar"};

where SIZEshould be replaced by a number.

char arr[][4] = {"foo", "bar"};

will work with strings, but will not if you use:

char arr[][4] = {"foo", "fubar"};

When such a line compiles, gcc prints the following warning:

: [ ]      char arr [] [4] = { "foo", "fubar" };

, . .

0

Source: https://habr.com/ru/post/1548157/


All Articles