-
adding extra to char*
Hi,i was doing c program to read files and manipulate it.
i got then, i wanted to add a extra letter at the end? how to do it?any one can tell?
that means i wanted
Code:
char *word="test";
word[4]='z'; //adding z to the end so i can get 'testz'
word[5]='\0';
//word would now be 'testz' instead of 'test'
the above doesnt work.any idea to go about adding a extra letter at the end.
-
Well, the first step would be to make sure that there is space for the extra letter. The simplest way to do that is to create an array instead of just pointing to a literal constant [that is, your "test" string].
The other problem, which is automatically solved too by the above approach, is that your constant "test" is really a CONSTANT - you can't modify the content of the memory where it resides.
So here's how to do it:
Code:
char word[6]="test";
word[4]='z'; //adding z to the end so i can get 'testz'
word[5]='\0';
--
Mats
-
If you want to add an extra string rather than an extra character, you could assign word[4] and word[5] etc, but it would be rather tedious. A better solution in this case is to use strcat().
Code:
#include <stdio.h>
#include <string.h> /* for strcpy() and strcat() */
int main() {
char *firstname = "John", *lastname = "Doe"; /* constant string literals, cannot be modified */
char name[100];
strcpy(name, firstname); /* strcpy(), not strcat(), for an uninitialized string */
strcat(name, " ");
strcat(name, lastname);
printf("Hello, %s!\n", name);
return 0;
}
Alternatively, you could use sprintf().
Code:
sprintf(name, "%s %s", firstname, lastname);