Although I am using C++, as a requirement I need to use const char* arrays instead of string or char arrays. Since I am new, I am required to learn about how to use const char*. I have declared my const char* array as const char* str[5]
. At a later point in the program I need to populate each on of the 5 elements with values.
However, if I try to assign a value like this:
const char* str[5];
char value[5];
value[0] = "hello";
str[0] = value[0];
It will not compile. What is the proper way to add a char array to char to a const char* array and then print the array? Any help would be appreciated. Thanks.
The string "hello"
is made up of 6 characters, not 5.
{'h', 'e', 'l', 'l', 'o', '\\0'}
If you assign the string when you declare value
, your code can look similar to what your currently have:
char value[6] = "hello";
If you want to do it in two separate lines, you should use strncpy()
.
char value[6]; strncpy(value, "hello", sizeof(value));
To place a pointer to value
in the list of strings named str
:
const char * str[5]; char value[6] = "hello"; str[0] = value;
Note that this leaves str[1]
through str[4]
with unspecified values.
Various methods to populate const char* str[5]
later point in the program.
int main(void) {
const char* str[5];
str[0] = "He" "llo"; // He llo are string literals that concat into 1
char Planet[] = "Earth";
str[1] = Planet; // OK to assign a char * to const char *, but not visa-versa
const char Greet[] = "How";
str[2] = Greet;
char buf[4];
buf[0] = 'R'; // For a character array to qualify as a string, need a null character.
buf[1] = 0; // '\0' same _value_ as 0
str[3] = buf; // array buf converts to address of first element: char *
str[4] = NULL; // Do not want to print this.
for (int i = 0; str[i]; i++)
puts(str[i]);
return 0;
}
.
Hello
Earth
How
R
value[0] = "hello";
How can this hold "hello". It can hold only one character.
Also value[5]
is not enough for this . There will be no space for '\\0'
and program will exhibit UB .
Thus either use value[6]
-
char value[6];
strncpy(value,"hello",sizeof value);
Or declare like this -
char value[]="hello";
And after that just make the pointer point to this array. Something like this-
str[0]=value;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.