How can I concatenate strings this way?
For example:
char *txt = "Hello";
txt=txt+"World!";
I tried it but it wasn't.
How can I concatenate strings this way?
For example:
char *txt = "Hello";
txt=txt+"World!";
I tried it but it wasn't.
txt
is a pointer and memory should be allocated to it.
It is good to have the below checks
The amount of memory which needs to allocated can be calculated by
size_t size = strlen("Hello") + strlen("World");
char *txt = malloc(size + 1);
Check the return value of malloc() before accessing it.
if(txt != NULL)
Dynamically this can be done:
char *txt = malloc(size+1); /* Number of bytes needed to store your strings */
strcpy(txt,"Hello");
strcat(txt,"World");
The allocated memory should be freed after using it like
free(txt);
Alternatively you can have
char txt[30];
strcpy(txt,"Hello");
strcat(txt,"World");
here is classic way to concat strings:
char *txt = "Hello";
char *txt2 = "World!";
char *txt3 = malloc(strlen(txt) + strlen(txt2) + 1); // don't forget about ending \0
strcpy(txt3,"Hello");
strcat(txt3,"World");
don't forget to free allocated memory
Avoid the memory leak using malloc - use arrays
i.e.
char txt[100];
strcpy(txt, "hello");
strcat(txt, "world");
This is covered in all C text books
To do it properly you have many options you could declare an array of char
and use what @EdHeal suggested, but you should know in advance the length of both strings combined or you can overflow the array, and that is undefined behavior.
Or, you cold use dynamic memory allocation, but that is more complicated than just calling malloc
and strcpy
since you need to be very careful.
First of all, you have to know that in c strings require a '\0'
character at the end of the string so when you allocate memory you should account for it.
The length of the string is obtained by means of the strlen
function, which you should try to use only once per string since it computes the length, so it's expensive and it's redundant to use it more than once for the same string.
When using malloc
the system may run out of memory, in that case malloc
will return a special value NULL
, if it did, any operation on the resulting pointer will be undefined behavior.
Finally when you no longer need the constructed string, you have to release resources to the operating system, usgin free
.
This is an example of what I mean
char *text;
size_t lengthOfHello;
size_t lengthOfWorld;
lengthOfHello = strlen("Hello");
lengthOfWorld = strlen("World");
text = malloc(1 + lengthOfHello + lengthOfWorld);
if (text != NULL)
{
strcpy(text, "Hello");
strcat(text, "world");
/* ... do stuff with text ... */
free(text);
}
the terminating '\0'
is already in "Hello"
and it will be copied by strcpy
.