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/