这是我的代码的一部分。我将文本文件的一些行放入 array1,我选择了数字 28,但它必须是我存储的每一行的不同数字。我需要为每行的实际长度分配空间,但我不确定如何找到每个字符串的长度,因为 sizeof(str) 总是给我 100。
while (fgets(str, sizeof(char)*100, fp) != NULL) {
array1[j] = (char *)malloc(sizeof(char)*28);
strcpy(array1[j], str);
j++;
//其余代码 }
最佳答案
allocating enough space for the actual length of the string
(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]
。
关于c - 为字符串的实际长度分配足够的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46393099/