c - 我从文件中读取一个字符串并将其存储到一个数组中,但是我如何知道数组的长度呢?

标签 c arrays string input

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main()
{
    int i = 0, len1=0, len2=0;
    int BUFSIZE = 1000;
    char* string1[20];
    char* string2[20];
    FILE *fp1 = fopen("input1.txt", "r");
    FILE *fp2 = fopen("input2.txt", "r");
    if ((fp1 == 0)||(fp2 == 0)){
        fprintf(stderr, "Error while opening");
        return 0;
    }
    string1[i] = (char*)malloc(BUFSIZE);
    string2[i] = (char*)malloc(BUFSIZE);
    while (fgets(string1[i], BUFSIZE, fp1)) {
        i++;
        len1+=strlen(string[i]);
        string1[i] = (char*)malloc(BUFSIZE);
        len1+=strlen(string1[i]);
    }

    i = 0;
    while (fgets(string2[i], BUFSIZE, fp2)) {
        i++;
        string2[i] = (char*)malloc(BUFSIZE);
    }

    printf("Output: \n");
    srand(time(NULL));
    int j = rand()%i;
    int k = (j+1)%i;
    fflush(stdout);
    printf("%d - %s %d -%s", j, string1[j], k, string1[k]);
    printf("%d - %s %d -%s", j, string2[j], k, string2[k]);
    printf("\n");
    printf("%d", len1);

    int x;
    for(x = 0; x<i; x++){
        free(string1[x]);
        free(string2[x]);
    }
    scanf("%d", x);
    fclose(fp1);
    fclose(fp2);
    return 0;
}

感谢user1807597的帮助,我终于实现了读取两个字符串并存入数组。但是我仍然无法获取数组的长度,我尝试将 len+=strlen(string[i]);在 while 循环中,但编译器在调试时中断。有人知道为什么吗?谢谢!

最佳答案

数组的长度有两个主要选择。

  1. 你把它做得足够大,你认为你永远不会使用更多的条目。

    enum { MAX_LINES = 16 * 1024 };
    char *lines[MAX_LINES];
    size_t num_lines = 0;
    
  2. 您对数组进行动态分配。

    char **lines = 0;
    size_t max_lines = 0;
    size_t num_lines = 0;
    
    ...
    
    if (num_lines >= max_lines)
    {
        size_t new_lines = max_lines * 2 + 2;
        char **space = realloc(lines, new_lines * sizeof(*space));
        if (space == 0)
            ...deal with out of memory...
        lines = space;
        max_lines = new_lines;
    }
    

两个系统都可以工作。动态分配在您执行的前几次有点繁琐,但是直到您用完内存时才会遇到问题,而现在内存用完需要很长时间。如果你猜错了,固定分配可能会用完空间,如果你只处理小文件,名义上会浪费内存。如今,“浪费”的内存通常很小。

哪个更好取决于您希望程序处理的问题的规模。如果它们很小,固定但慷慨的分配是明智且更容易的。如果它们很大,动态分配会更明智。

关于c - 我从文件中读取一个字符串并将其存储到一个数组中,但是我如何知道数组的长度呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13318560/

相关文章:

arrays - 快速检索第一个字典值

javascript - 如何在按钮单击时检查 javascript 中的许多自定义函数中最后调用的是哪个函数?

python - 为什么字符串方法在 for 循环中使用时停止对对象列起作用

mysql - MySQL 中是否有替代 CONCAT() 的方法?

C 编译器检查 typedef'ed void *

函数 'read' 的冲突类型?

c - 使用 system tap 时如何避免 "probe overhead exceeded threshold"错误?

将 C 处的 WHILE 循环更改为 FOR 循环

python - Numpy:基于单独的向量交换二维数组的位置

python - 使用 Python 的 lambda 函数排列字符串的数量