How to assign values to const char* array and print to screen
Solution 1
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 namedstr
:const char * str[5]; char value[6] = "hello"; str[0] = value;
Note that this leaves
str[1]
throughstr[4]
with unspecified values.
Solution 2
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
jshapy8
Using software to solve problems. Currently doing it with iOS apps written in Swift.
Updated on July 09, 2022Comments
-
jshapy8 almost 2 years
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.
-
Captain Obvlious over 8 yearsHow about
char value[] = "hello";
? -
Bill Lynch over 8 years@CaptainObvlious: Sure. But it's not obvious to revolution how many bytes that occupies.
-
Fredrick Gauss about 7 years@BillLynch, your last example
str[0] = value;
seems very dangerous. It assigns 4 byte pointer address value to 1 byte char value place. -
Bill Lynch about 7 years
str
in this example is a list of strings.