首先,这些参数有主要功能。
char ***matrix;
int line, maxCollumn, i, j;
int lineData[100];
然后我调用函数
PutFirstAndLast(&matrix, &line, &maxCollumn, lineData);
此函数用于动态分配矩阵并返回其行数和列数。 lineData用于存储每行上有多少项,因为稍后在函数中我将用“”填充“空”空格。
我的麻烦功能有这个标题
int PutFirstAndLast(char**** matrixPointer, int *line2, int *maxCollumn2, int *lineArray)
在这个函数中,我将生成一个以半延迟方式“数组”调用的新矩阵,我将为新的“数组”分配内存,以便将每个单词从文件“in.txt”中放入其中。
int PutFirstAndLast(char**** matrixPointer, int *line2, int *maxCollumn2, int *lineArray)
{
FILE *inputFile;
char buffer[100], *p;
char ***array;
int i, j, collumn, maxCollumn = 0, line = -1;
inputFile = fopen("in.txt", "r");
while (fgets(buffer, 100, inputFile))
{
line++;
collumn = 0;
if (line == 0)
array = (char***)malloc(sizeof(char**));
else
array = (char***)realloc(array, sizeof(char**)* (line + 1) );
p = strtok(buffer, " \n");
while (p)
{
//taking each word and allocating a space for it
if (collumn == 0)
array[line] = (char**)malloc(sizeof(char*));
else
array[line] = (char**)realloc(array[line], sizeof(char*)* (collumn + 1));
array[line][collumn] = (char*)malloc(sizeof(char)* strlen(p) + 1);
strcpy(array[line][collumn], p);
collumn++;
p = strtok(NULL, " \n");
}
// Here i count what is the maximum numbers of items on a line
lineArray[line] = collumn;
if (collumn > maxCollumn)
maxCollumn = collumn;
}
// Here i add "" in the "empty spaces.
for (i = 0; i < line + 1; i++)
{
for (j = lineArray[i]; j < maxCollumn; j++)
{
array[i] = (char**)realloc(array[i], sizeof(char*)* maxCollumn);
array[i][j] = (char*)malloc(sizeof(char)* 10);
strcpy(array[i][j], "");
}
}
fclose(inputFile);
*matrixPointer = array;
*maxCollumn2 = maxCollumn;
*line2 = line;
return 0;
}
问题是当我来到主要而且我这样做时
for (i = 0; i < line + 1; i++)
{
for (j = 0; j < maxCollumn; j++)
{
printf("%s", matrix[i][j]);
matrix[i][j] = (char*)realloc(matrix, sizeof(char)* 11);
}
}
对于项目矩阵[2] [0],存在错误“访问违规读取位置”。
如果我这样做for (i = 0; i < line + 1; i++)
{
for (j = 0; j < maxCollumn; j++)
{
printf("%s", matrix[i][j]);
// matrix[i][j] = (char*)realloc(matrix, sizeof(char)* 11);
}
}
没有问题,我在矩阵中显示的所有单词都显示在屏幕上
我的文字模型是:
etesta este astru
de mext pentru bun
examen multa programare
在“空”空格中添加“”我指的是:puttin the“in the arraylike this:
etesta este astru
de mext pentru bun
examen multa programare
答案 0 :(得分:5)
使用realloc
指针调用matrix
函数时应该是matrix[i][j]
:
matrix[i][j] = realloc(matrix[i][j], sizeof(char)* 11);
或者,如果你想保护自己免受失败:
char *temp = realloc(matrix[i][j], sizeof(char)* 11);
if (temp != NULL)
matrix[i][j] = temp;