How to add two string in C?
Have a look at my program that I have made so far.
#include <stdio.h>
int main()
{
char samrat[10]="*";
char string[1]="*";
samrat=samrat+string;
}
How to add two string in C?
Have a look at my program that I have made so far.
#include <stdio.h>
int main()
{
char samrat[10]="*";
char string[1]="*";
samrat=samrat+string;
}
Use standard C function strcat
declared in header <string.h>
. For example
#include <string.h>
//...
strcat( samrat, string );
Another approach is to create dynamically a new string that will contain the concatenation of these two strings. For example
#include <string.h>
#include <stdlib.h>
//...
char *s = malloc( strlen( samrat ) + strlen( string ) + 1 );
if ( s != NULL )
{
strcpy( s, samrat );
strcat( s, string );
}
//...
free( s );
As for your statement
samrat=samrat+string;
then array designators are converted (with rare exceptions) to pointers to their first elements in expressions. So you are trying to add two pointers. This operation for pointers is not defined in C. And moreover arrays are non-modifiable lvalues. You may not assign an array with an expression.
samrat + string
will attempt to add together two pointers of type char*
, with a meaningless result.
Use strcat
to concatenate two strings: strcat(samrat, string);
. Don't forget to ensure that the samrat
buffer is large enough to accommodate the result.