将一个字符串添加到另一个字符串

Yas*_*ati 1 c string malloc function

锻炼:

编写一个函数,在作为参数给出的 CH2 字符串的末尾添加 CH1 字符串后,返回一个 CH 字符串。

这是我的代码:

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

char *ajout(char ch1[], char ch2[]);

int main() {
    char ch1[] = "hello";
    char ch2[] = "ooo";
    char *ch = ajout(ch1, ch2);
    printf("%s",ch);
    return 0;
}

char *ajout(char ch1[], char ch2[]) {
    char *ch;
    int nb = 0;
    for (int i = 0; ch1[i] != '\0'; i++) {
        ch[i] = ch1[i];
        nb++;
    }
    int i = 0;
    for (i; ch2[i] != '\0'; i++) {
        ch[nb] = ch2[i];
        nb++;
    }
    return ch;
}
Run Code Online (Sandbox Code Playgroud)

程序执行后的预期结果: helloooo

Eya*_*lan 5

首先,C 中的字符串只是指向以第一个空字符结尾的 char 数组的指针。C 中没有字符串连接运算符。

此外,为了在 C 中创建一个新数组 - 您需要使用malloc. 但是,在ajout函数中,您没有为ch. 解决方案:

const size_t len1 = strlen(ch1); //get ch1 length
const size_t len2 = strlen(ch2); //get ch2 length
char *ch = malloc(len1 + len2 + 1); //create ch with size len1+len2+1 (+1 
                                    //for null-terminator)
Run Code Online (Sandbox Code Playgroud)

我看你复制的每一个字符ch1,并ch2进入ch一个接一个。更好的解决方案是复制ch1ch2使用memcpy. 此外,在使用分配内存后malloc,您需要使用free以下方法解除分配字符串:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* ajout(const char *ch1, const char *ch2)
{
    //get length of ch1, ch2
    const size_t len1 = strlen(ch1);
    const size_t len2 = strlen(ch2);

    //create new char* array to save the result 
    char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here

    //copy ch1, ch2 to result
    memcpy(result, ch1, len1); 
    memcpy(result + len1, ch2, len2 + 1); // +1 to copy the null-terminator
    return result;
}

int main()
{
    char ch1[] = "hello";
    char ch2[] = "ooo";
    char *ch = ajout(ch1,ch2);
    printf("%s",ch);
    free(ch); // deallocate the string
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:你好

您可以阅读有关memcpy 此处malloc 此处的更多信息。