【发布时间】:2016-11-17 04:35:42
【问题描述】:
我正在尝试读取从标准输入重定向到二维数组的文件中的特定字符,我不确定我是否为二维数组正确分配内存。文件中的第一行是我要复制的矩阵的尺寸。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "QueueImplementation.c"
int tester(char *s, int cnt)
{
int num1, num2;
if(cnt == 0)
{
sscanf(s, "%d %d", &num1, &num2);
if(num1 < 2 || num1 > 20 || num2 < 2 || num2> 20)
{
printf("Incorrect Matrix Dimensions!");
printf("\n");
}
return num1;
}
}
void allocateMem(char ***cell, int n, int m)
{
*cell=(char**)malloc(n*sizeof(int*));
for(int i=0;i<n;i++)
*cell[i]=(char*)malloc(m*sizeof(int));
}
int main(){
char buffer[200];
int j,max_row,max_col;
int count = 0;
int i = 0;
while (fgets(buffer, sizeof buffer, stdin))
{
if(count == 0)
max_col = tester(buffer, count);
count++;
}
max_row = count - 1;
char** cell;
allocateMem(&cell, max_row, max_col);
while (fgets(buffer, sizeof buffer, stdin))
{
for(j = 0;j<max_col;j++)
{
if(buffer[j] != '\n' && buffer[j] != ' ' && buffer[j] < '0')
cell[i-1][j] = (char) buffer[j];
}
i++;
}
for (i = 0;i<max_row;i++)
{
for (j = 0;j<max_col;j++)
{
printf("%c", cell[i][j]);
}
}
}
我重定向的测试文件包含
12 10
oooooooooooo
ooooooooooo.
oooooooo....
se.......ooo
oooooooo....
主要由“o”和“.”组成除了单个“s”和“e”。 12 和 10 是我要复制的矩阵的维度,因此预期的输出应该是由 o 和 . 以及单个“s”和“e”组成的矩阵。
【问题讨论】:
-
*cell[i]=(char*)malloc(m*sizeof(int));-->(*cell)[i]=malloc(m*sizeof(char));, 还有*cell=(char**)malloc(n*sizeof(int*));-->*cell=malloc(n*sizeof(char*)); -
cell[i-1][j] = (char) buffer[j];-->cell[i][j] = buffer[j]; -
for (j = 0;j<max_col;j++) { printf("%c", cell[i][j]);?? -
如果读取所有文件以计算行数,则没有要读取的数据。
-
您的代码中没有二维数组。只是凌乱的三星级编程。请阅读How do I correctly set up, access, and free a multidimensional array in C?。
标签: c file matrix segmentation-fault stdin