casting error arising upon appending a string to another one

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

1 answer

  • answered 2021-07-23 10:28 Vlad from Moscow

    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 );
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum