c - 如何预先确定 malloc 的大小以连接字符串数组?

标签 c string pointers

Implement the append function that has the prototype below. The function returns a string that represents the concatenation of all the strings present in an array of strings. For this problem, you can assume the end of the parameter array is marked by NULL. You need to allocate memory for the resulting string. You may not modify the array parameter.

char* append(char *data[]); 

我不明白如何确定 malloc 指针的大小。

最佳答案

首先,要知道一个字符串的大小,可以使用strlen来自图书馆string.h .如果你想计算所有大小的总和,你可以使用一个循环并对所有 strlen 求和。 s,并添加 1对于终端 NUL字符,像这样:

char* append(char *data[]) {
    char **cur, *res;
    size_t len = 0;

    for (cur = data; *cur != NULL; *cur++)
        len += strlen(*cur);

    res = malloc(len + 1);

    // Now you can concatenate the strings...
}

哦,别忘了检查 malloc 返回的指针有效(即不是 NULL )。

关于c - 如何预先确定 malloc 的大小以连接字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49023189/

相关文章:

c++ - 使用Linux pread可以避免 “unavailability of data for reading written by a different thread”吗?

c - 增加堆栈大小 : typical issues?

pointers - 通过 `mem::transmute()` 指针存储泛型

javascript - 如何匹配引号内的搜索词

c++ - 如何初始化这个指针数组?

c - 为什么我们向 scanf 提供地址?

c - 有没有办法检查文件是否是 SQLite3 数据库?

c++ - 有限域上超定系统解的存在性

python - 使用循环过滤带有关键字列表的字符串列表

c++ - 什么时候在 C++ 程序的开头使用 '#include <string>'?