1

I am trying to append a certain string (characters array) to another one as suggested here: https://stackoverflow.com/questions/10279718/append-char-to-string-in-c#:~:text=To%20append%20a%20char%20to%20a%20string%20in,because%20the%20given%20literal%20string%20cannot%20be%20modified

My code is as follows:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){

char *mystring="Life";
int length_string=strlen(mystring);

char *string_continuation=" is life";
int length_continuation=strlen(string_continuation);

char *new_word=malloc(length_string+length_continuation+1);
strcpy(new_word,mystring);

for (int i=0; i<length_string; i++){
    
    
new_word[length_string+i]=string_continuation[i];

}
new_word[length_continuation+length_string]="\0";

printf("The final word is %s", new_word);
free (new_word);

return 0;
}

However, I am getting the typical error:

assignment makes integer from pointer without a cast [-Wint-conversion]

which refers to line:

 new_word[length_continuation+length_string]="\0"; 

Does anyone know why such error arises? Many thanks

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Oriol
  • 75
  • 5

1 Answers1

3

In this assignment statement

new_word[length_continuation+length_string]="\0";

the right operand of the assignment is string literal "\0" that has the type char[2] and is implicitly converted in the expression to the type char *.

On the other hand, the left operand has the type char. So the compiler issues the error.

You need to write

new_word[length_continuation+length_string]='\0';

using integer character constant '\0'.

Pay attention that there is a typo in the for loop. Instead of

for (int i=0; i<length_string; i++){

there must be

for (int i=0; i<length_continuation; i++){

Also instead of the for loop you could just use the standard C function strcat as for example

strcat( new_word, string_continuation );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335