I have this string that is presented in the form of character array temp. And I want to insert this character array to another array temp_list and then print out the contents of this array. In other words, storing many character arrays in a single array. Can anyone tell me if this is possible and how can I make it work?
This is an example of what I am trying to accomplish:
int main()
{
char temp[5] = "begin";
char temp_list [10];
temp_list[0] = temp;
for (int i = 0; i < strlen(temp_list); i++)
{
printf("Labels: %s,", temp_list[i]);
}
}
When I run this program, it prints out gibberish.
Any form of guidance would be very appreciated. Thank you.
Edit:
Thank you for the answers. They are all really helpful. But I have another question... what if I have multiple character arrays that I want to insert to temp_list? Using strcpy multiple times seem to not work, since I am assuming the function basically replaces the entire content of the temp_list with the string passed with strcpy?
There are a bunch of misconceptions regarding strings. Your array temp needs to be big enough to also store the null-terminator, so it needs a size of at least 6 in this case:
char temp[6] = "begin"; // 5 chars plus the null terminator
To copy the string, use strcpy:
char temp_list[10];
strcpy(temp_list, temp);
To print it, pass temp_list, not temp_list[i], also you don't need that loop:
printf("%s\n", temp_list);
The final program could look like this:
int main()
{
char temp[6] = "begin";
char temp_list[10];
strcpy(temp_list, temp);
printf("%s\n", temp_list);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With