String concatenation without strcat in C

前端 未结 7 772
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 13:44

I am having trouble concatenating strings in C, without strcat library function. Here is my code

#include
#include
#include<         


        
7条回答
  •  不思量自难忘°
    2021-01-13 14:43

     char a1[] = "Vivek";
    

    Will create a char array a1 of size 6. You are trying to stuff it with more characters than it can hold.

    If you want to be able to accommodate concatenation "Vivek" and "Ratnavel" you need to have a char array of size atleast 14 (5 + 8 + 1).

    In your modified program you are doing:

    char *a1=(char*)malloc(100);  // 1
    a1 = "Vivek";                 // 2
    

    1: Will allocate a memory chunk of size 100 bytes, makes a1 point to it.
    2: Will make a1 point to the string literal "Vivek". This string literal cannot be modified.

    To fix this use strcpy to copy the string into the allocated memory:

    char *a1=(char*)malloc(100);  
    strcpy(a1,"Vivek");
    

    Also the for loop condition i will not copy last character from the string, change it to i

    And

    a1[i]='\0';
    

    should be

    a1[i + len]='\0';
    

    as the new length of a1 is i+len and you need to have the NUL character at that index.

    And don't forget to free your dynamically allocated memory once you are done using it.

提交回复
热议问题