嗯,这就是您明确接受的答案所做的,这是一个非常好的主意,因为您必须以某种方式确定特定行包含多少列。另一个方法是让每一行中的特殊值确定结尾(如'\0'
字符串)。要拥有它,您可以按如下方式更改代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getColCount(FILE *fin){
long fpos = ftell(fin);
int count = 0;
char buff[BUFSIZ];
while(fgets(buff, sizeof(buff), fin)){
char *p;
for(p=strtok(buff, " \t\n");p;p=strtok(NULL, " \t\n"))
++count;
if(count)break;
}
fseek(fin, fpos, SEEK_SET);
return count;
}
int main(void){
FILE *fp;
int *key1[2];
if((fp = fopen("/Users/doc/test.txt", "rt")) == NULL){
printf("\nCannot open file");
exit(1);
}
for(int i = 0; i < 2; ++i){
int size = getColCount(fp);
// size+1 is still necessary, the additional element is now needed for the delimiting value instead of the number of elements
key1[i] = malloc((size+1)*sizeof(int));
/* CHANGE: don't store size in col 0
if(key1[i]){
key1[i][0] = size;//length store top of row
} else {
fprintf(stderr, "It was not possible to secure the memory.\n");
exit(2);
}
now we just do: */
if(!key1[i]){
fprintf(stderr, "It was not possible to secure the memory.\n");
exit(2);
}
/* CHANGE: we start with index 0 */
//for(int j = 1; j <= size ;++j){
for(int j = 0; j < size ;++j){
fscanf(fp, "%d", &key1[i][j]);
}
/* CHANGE: we add a final value to determine the end of the row */
key[i][size] = -1; // choose a value that cannot occur in your data
}
fclose(fp);
{//check print and dealocate
for(int i = 0; i < 2 ; ++i){
for(int j = 1; j <= key1[i][0]; ++j)
printf("%d ", key1[i][j]);
printf("\n");
free(key1[i]);
}
}
return 0;
}