分配的字符串
演员在(char *)malloc(sizeof(char)*28);
不需要(char *)
的实际长度足够的空间。
使用strlen(str)
@M Oehm查找长度。此长度不包括'\0'
。
找到大小需要加1到长度。
分配为字符串大小,而不是长度。
最好使用size_t
进行字符串长度/大小计算。 int
可能不足。
的问题是这样写一个字符串复制功能。研究通用的strdup()
函数。
char *s96_strdup(const char *s) {
size_t length = strlen(s); // Get the string length = does not include the \0
size_t size = length + 1;
char *new_string = malloc(size);
// Was this succesful?
if (new_string) {
memcpy(new_string, s, size); // copy
}
return new_string;
}
用法。 fgets()
读取行,其通常包括'\n'
。
char str[100];
while (j < JMAX && fgets(str, sizeof str, fp) != NULL) {
array1[j] = s96_strdup(str);
j++;
}
记住最终会为每个分配的字符串调用free(array1[j]
。
你想'''strlen',但不要忘记添加一个空终止符。 –
你可以使用'stdlib.h'的'strlen()'函数 – krpra
另外,请把sizeof(char)* 100'改为'sizeof(str)'。假设'str'是一个数组,而不是传递给函数的指针(或数组)。这是发布不完整代码的麻烦。 –