Reputation: 360
I know how to do it on the string, so "hello world"
would be "hello world\n"
. But if I have something like char *str = "helloworld".
and I want to add \n at the end of str, how am I supposed to do it?
Upvotes: 5
Views: 24544
Reputation: 63
As others have pointed out, you can't add/concatenate more characters to the end of str
in your code example without some form of reallocation of space.
But if I may respond to what might be the real aim of your question (you asked specifically about appending a newline and not just any text, which makes me think you are trying to format text for output), you can easily add '\n'
alongside str
when you send it to stdout:
printf("%s\n", str);
In fact, you can prepend/append whatever you like before/after str
by altering the format string:
printf(">>> %s <<<\n", str);
printf()
has lots of "friends", e.g. fprintf()
for outputting to a file instead of stdout, that behave similarly.
This way, you don't need to worry about reallocating anything just to append a newline or otherwise format the text for output.
Does that help?
Upvotes: 0
Reputation: 3234
You have declared string literals, which cannot be modified. You will need to do something like:
char *str;
str = malloc (sizeof (char) * MAX_SIZE);
strcpy (str, "HelloWorld");
strcat (str, "\n");
or, You should use an array.
Upvotes: 2
Reputation: 780869
You can't do this.
When you use
char *str = "helloworld";
str
points to a string that cannot be modified. It also doesn't have any extra space available beyond the characters in the literal, so you can't extend its size.
If you need a string that's the same as str
but with an added newline, you need to make a copy first.
char *newstr = malloc(strlen(str) + 2);
strcpy(newstr, str);
strcat(newstr, "\n");
Remember to add 2 to the length: 1 byte for the newline being added, another for the trailing null.
See Why do I get a segmentation fault when writing to a string initialized with "char *s" but not "char s[]"? for more information about the differences between using
char str[] = "helloworld";
and
char *str = "helloworld";
Upvotes: 12