#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 循环中,但编译器在调试时中断。有人知道为什么吗?谢谢!
最佳答案
数组的长度有两个主要选择。
你把它做得足够大,你认为你永远不会使用更多的条目。
enum { MAX_LINES = 16 * 1024 }; char *lines[MAX_LINES]; size_t num_lines = 0;
您对数组进行动态分配。
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/