c - 为字符串的实际长度分配足够的空间

标签 c

这是我的代码的一部分。我将文本文件的一些行放入 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/

相关文章:

c - 根据我的要求使按钮看起来禁用/灰色

c - 我的程序似乎没有终止;为什么?

c - 如何通过一次在数组中取出 2 个项目来将权重添加到 sack 中?

c - 打印 strtok 结果后 vprintf() 中的 SIGSEGV

c - 独特的字符串生成器

c - 在 C 中打破递归的惯用方法是什么?

c - 对准控制上的星型练习

c - Ada 向 c 发送字节缓冲区

c - 大小 1 的读取无效

c++ - C和C++中函数赋值给变量的区别