-4

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;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • 1
    did you try `strcat()` ? – Shark Aug 17 '16 at 15:09
  • @deamentiaemundi: No; not really. https://www.google.com/search?q=c+add+strings – SLaks Aug 17 '16 at 16:36
  • @SLaks Reseaching yourself? Asking Google even? No, *that* would be waaay too much! ;-) But serious: it was meant as a little stinger for those users here who think that every poster is highly fluent in English and I was quite serious with "third or fourth" language. Be a more patient, pleeease! – deamentiaemundi Aug 17 '16 at 18:50

2 Answers2

3

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Perhaps you should recommend him to allocate/malloc a new buffer equal to the length of both strings? – Shark Aug 17 '16 at 15:10
1

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.

P45 Imminent
  • 8,319
  • 4
  • 35
  • 78