【问题标题】:Adding a string to another string将一个字符串添加到另一个字符串
【发布时间】:2020-04-13 07:13:54
【问题描述】:

运动:

编写一个函数,在作为参数给出的 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;
}

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

【问题讨论】:

  • char *ch; 没有分配内存(在函数ajout 中)。试试ch = malloc(1 + strlen(ch1) + strlen(ch2)); 你应该在连接的字符串中添加一个 nul 终止符。
  • 尝试 malloc 并阅读有关缓冲区溢出的信息
  • 这能回答你的问题吗? How do I concatenate two strings in C?
  • 谢谢@weathervane,这就是我所做的:` int c = malloc(1 + strlen(ch1) + strlen(ch2));字符 ch[c]; *ch=ajout(ch1,ch2);` 但还是不行,我的代码有什么问题?
  • 发布问题中的任何更新(完整实施),以便我们对其进行修改。

标签: c string function malloc


【解决方案1】:

首先,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)

我看到你将ch1ch2 的每个字符一个一个地复制到ch 中。更好的解决方案是使用memcpy 复制ch1ch2。另外,在使用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;
}

输出: 你好

你可以阅读更多关于memcpyheremallochere的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    相关资源
    最近更新 更多