how to add char to end of string in C?

0

i want to success two cases

  • language C

Code

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void append(char* s, char c){
        int len = strlen(s);
        s[len] = c;
        s[len+1] = '\0';
}
int main()
{
    char resultat[]="";
    char str[]="hello world!";
    int len=strlen(str);

    printf("******* case 01 *******");
    for(int i=0;i<len;i++){
        strcat(resultat,str[i]);
    }
    printf("resultat = %s",resultat);



    printf("******* case 02 *******");
    for(int i=0;i<len;i++){
        append(resultat,str[i]);
    }
    printf("resultat = %s",resultat);


    return 0;
}

How can I add chars to a string? I tried this but I get this error:

******* case 01 *******
Process returned -1073741819 (0xC0000005)   execution time : 4.676 s
Press any key to continue.
c
asked on Stack Overflow Mar 6, 2020 by reguieg younes • edited Mar 6, 2020 by ks1322

1 Answer

1

In C you need to make sure the destination variable has enough memory to store the stuff you want to copy there.

strcat needs a string (char *).

Here is my fixed version of your code

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

void append(char *s, char c)
{
    int len = strlen(s);
    s[len] = c;
    s[len + 1] = '\0';
}

int main()
{
    char str[] = "hello world!";
    int len = strlen(str);
    char resultat[len * 3];
    resultat[0]='\0';
    printf("******* case 01 *******\n");
    char tmp[2];
    tmp[1] = '\0';
    for (int i = 0; i < len; i++)
    {
        tmp[0] = str[i];
        strcat(resultat, tmp);
    }
    printf("resultat = %s\n", resultat);
    printf("******* case 02 *******\n");
    for (int i = 0; i < len; i++)
    {
        append(resultat, str[i]);
    }
    printf("resultat = %s\n", resultat);
    return 0;
}
answered on Stack Overflow Mar 6, 2020 by Eugenio Hernan • edited Mar 6, 2020 by Eugenio Hernan

User contributions licensed under CC BY-SA 3.0