【发布时间】:2018-12-03 18:28:04
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STRING_LENGTH 100
int main(int argc, char const *argv[])
{
FILE* file;
char ***myTable;
/* I want to declare a matrix which will contain a string in each cell */
int end = 1;
int row = 0;
/* space declaration */
myTable = (char ***) malloc(sizeof(char**));
myTable[0] = (char **)malloc(3 * sizeof(char*));
for(int j = 0; j < 3; j++)
myTable[0][j] = (char *)malloc(MAX_STRING_LENGTH * sizeof(char));
file = fopen(argv[1], "r");
while(end) {
//filling the matrix from the file no matter how many row
//the file has
for(int j = 0; j < 3; j++) {
fscanf(file, "%s", myTable[row][j]);
}
//adding one row every time i retrive the data
myTable = (char***) realloc(myTable, sizeof(**myTable) * (row+1));
row++;
if(getc(file) == EOF) end = 0;
}
fclose(file);
for(int rows = 0; rows < row; rows++) {
for(int col = 0; col < 3; col++)
printf("numero: %s ", myTable[rows][col]);
printf("\n");
}
return 0;
}
我正在尝试创建一个字符串矩阵,每当文件输入中有新行时,它都会增加行大小。该文件将如下所示。
3333333333 date1 u
2222222222 date2 e
在这种情况下,程序内部的矩阵将有 2 行 3 列。
在这个文件中
3333333333 date1 u
2222222222 date2 e
8888888888 date3 e
在这种情况下,程序内部的矩阵将有 3 行和 3 列;列将始终固定,但行数必须每次增加 1。
【问题讨论】:
-
myTable = (char***) realloc(myTable, sizeof(**myTable) * (row+1));应该是myTable = realloc(myTable, sizeof *myTable * (row+2));? -
仍然不工作,分段错误 11 一如既往