0

How can I take a C string pointer like

char *a = "asdf";

and change it so that it becomes

char *a = "\nasdf\n";
Paul
  • 779
  • 2
  • 9
  • 19

5 Answers5

0

When you assign string like tihs

char *a = "asdf";

you are creating a string literal. So it cannot be modified. It is already explained here.

Community
  • 1
  • 1
Krishnabhadra
  • 34,169
  • 30
  • 118
  • 167
0

You can't modify a string literal, so you would have to create a second string with that new format.

Or, if the formatting is just for display, you can hold off on creating a new string by just applying the formatting when you display it. Eg:

printf("\n%s\n", a);
PQuinn
  • 992
  • 6
  • 11
0

I don't know whether this is what you were looking for, but it looks like you want to concatenate strings: How do I concatenate const/literal strings in C?

Use "\n" as your first and last string, and the string given as the second one.

Community
  • 1
  • 1
SvenS
  • 795
  • 7
  • 15
0

You can't do that if you are using pointers to string literals, the reason being that a string literal is constant and can't be changed.

What you can do is declare an array, with enough space to accommodate the extra characters, something like

char a[16] = "asdf";

Then you can e.g. memmove to move the string around, and add the new characters manually:

size_t length = strlen(a);
memmove(&a[1], a, length + 1);  /* +1 to include the terminating '\0' */
a[0] = '\n';           /* Add leading newline */
a[length + 1] = '\n';  /* Add trailing newline */
a[length + 2] = '\0';  /* Add terminator */
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
-1
char* a = "asdf";
char* aNew = new char[strlen(a) + 2]; //Allocate memory for the modified string
aNew[0] = '\n'; //Prepend the newline character

for(int i = 1; i < strlen(a) + 1; i++) { //Copy info over to the new string 
    aNew[i] = a[i - 1];
}
aNew[strlen(a) + 1] = '\n'; //Append the newline character
a = aNew; //Have a point to the modified string

Hope this is what you were looking for. Don't forget to call "delete [] aNew" when you're finished with it to prevent it from leaking memory.

Taylor Bishop
  • 479
  • 2
  • 5
  • 18