我有一个全局char *
,在运行时,重新声明为指向声明为此way的2D数组的指针:
char (*A)[N][M] = malloc(sizeof(char[BUF_16][N][M]));
然后我将一个文件读入我的字符串A
矩阵,其中函数read2mat
使用子例程tokenizer2D
和removeEOF
,这里是代码:
void removeEOF(char *s)
{
char *newline = strchr( s, '\n' );
if ( newline )
*newline = 0;
}
void tokenizer2D(char *s, const char *delimiter, char *rowVec)
{
char *saveptr;
char *token = strtok_r(s, delimiter, &saveptr);
int j = 0;
while (token)
{
printf("token: %s ", token);
strcpy(&rowVec[j], token);
token = strtok_r(NULL, delimiter, &saveptr);
j++;
}
fputc('\n', stdout);
}
void read2mat(char filename[], const char delim[], int nrows, int ncols, int maxStrSize, char (*mat)[nrows][ncols])
{
ncols = fmax(ncols, 1);
// open the file for reading
FILE *f = fopen(filename, "r");
// make sure the file opened properly
if(NULL == f)
{
fprintf(stderr, "Cannot open file: %s\n", filename);
return;
}
char linea[maxStrSize];
int i=0;
while (fgets(linea, maxStrSize, f) != NULL)
{
removeEOF(linea); // elimina '\n' del string
tokenizer2D(linea, delim, &mat[i][0]);
linea[0] = '\0';
i++;
}
fclose(f);
}
然后我这样称呼它:
read2mat(myfile, delim, N, M, BUF_32, A);
虽然在tokenizer2D
函数中正确打印了从每行读取的标记,但我无法正确地将它们读入rowVec
的每个元素,可能是由于索引不良。
答案 0 :(得分:1)
更改为
char (*A)[M][BUF_32] = malloc(sizeof(char[N][M][BUF_32]));
...
void read2mat(char filename[], const char delim[], int nrows, int ncols, int maxStrSize, char (*mat)[ncols][maxStrSize])
或
void read2mat(char filename[], const char delim[], int nrows, int ncols, int maxStrSize, char mat[nrows][ncols][maxStrSize])
致电read2mat(myfile, delim, N, M, BUF_32, A);