简体   繁体   中英

how to add char to end of string in C?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM