将多条输入线加载到二维数组中 [英] Load multiple input lines into 2d array
本文介绍了将多条输入线加载到二维数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我不得不第一次使用2d数组,我很困惑. 我想将示例(输入)中的多行加载到该数组.
So I have to work for the first time with 2d array and I am confused. I want to load multiple lines like are in example (input), to that array.
123456
654321
123456
在array [0] [0]上应为1,array [1] [0]-6 .. 最重要的是,线的长度是随机的,但每条线都是相同的,将来我需要该数字.
On array[0][0] should be 1, array[1][0] - 6 .. The most important thing is that length of line is random but in every line same and I need that number for the future.
最好的方法是什么?感谢您的每一个建议,请不要对我苛刻.
What is the best way to do it? Thanks for every advice and please dont be harsh on me.
谢谢
推荐答案
像这样使用realloc
Use realloc like this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
FILE *fp = stdin;//or fopen
char line[100+2];
int rows = 0, cols = 0;
fgets(line, sizeof(line), fp);
cols = strlen(line)-1;//-1 for newline
char (*mat)[cols] = malloc(++rows * sizeof(char[cols]));
memcpy(mat[0], line, cols);
while(fgets(line, sizeof(line), fp)){
if((mat = realloc(mat, ++rows * sizeof(char[cols]))) == NULL){//In the case of a large file, realloc a plurality of times together
perror("realloc");
exit(EXIT_FAILURE);
}
memcpy(mat[rows-1], line, cols);
}
//fclose(fp);
//test print
for(int r = 0; r < rows; ++r){
for(int c = 0; c < cols; ++c){
printf("%c ", mat[r][c]);
}
puts("");
}
free(mat);
}
这篇关于将多条输入线加载到二维数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文