Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何用文件中的数据填充分配的二维数组?_C_Multidimensional Array - Fatal编程技术网

C 如何用文件中的数据填充分配的二维数组?

C 如何用文件中的数据填充分配的二维数组?,c,multidimensional-array,C,Multidimensional Array,我用C语言编写了以下代码: #define LINES 40 int i,j,k = 0; char **c; char tmp; // allocate key array memory if( (c = malloc(LINES*sizeof(char*))) == NULL) printf("Error allocating memory\n"); for(i=0;i<LINES;i++){ c[i] = malloc(10*sizeof(char)); } 如何

我用C语言编写了以下代码:

#define LINES 40
int i,j,k = 0;

char **c;
char tmp;

// allocate key array memory
if( (c = malloc(LINES*sizeof(char*))) == NULL)
  printf("Error allocating memory\n");

for(i=0;i<LINES;i++){
    c[i] = malloc(10*sizeof(char));
}

如何用该文件中的数据填充上面分配的数组(例如使用
fgets
fgetc
)?

如果字符串的长度是恒定的,如示例中所示,则可以使用
BUFSIZ
作为单词的最大长度来定义宏。注意:不要忘记在每个字符串的末尾计算
'\0'
字符。 在这种情况下,解决方案如下所示:

// create an array of strings
char ** array = (char **)calloc(LINES, sizeof(char *));

for (size_t i = 0; i < LINES; i++) {
    // allocate space for each string
    array[i] = (char *)calloc(1, BUFSIZ);
    // get the input
    fgets(array[i], BUFSIZ, stdin);
    // remove the '\n' character
    // from the end of the string
    array[i][strlen(array[i]) - 1] = '\0';
}
//创建字符串数组
char**array=(char**)calloc(line,sizeof(char*));
对于(大小i=0;i<行;i++){
//为每个字符串分配空间
数组[i]=(char*)calloc(1,BUFSIZ);
//获取输入
fgets(数组[i],BUFSIZ,stdin);
//删除“\n”字符
//从绳子的末端
数组[i][strlen(数组[i])-1]='\0';
}

每行有10个字符,因此您没有分配足够的空间将它们视为(以null结尾的)字符串-为了安全起见,数组的每行至少需要11个字符。如果程序遇到换行符前只有9个字符的行,该怎么办?11个或更多字符?如果少于40行,该怎么办?如果超过40行?你试过什么?您遇到了什么问题?您好@JonathanLeffler我已经尝试了上面的内容,只要
malloc(16*sizeof(char))
。问题是我不知道如何将10个字符的长度数据分配给2d数组(c)。另外,LINES是一个预定义的常量,其值为文件行数。我总是知道在读取1D数组之前的文件行数-然后您会怎么做?您会使用哪些功能?调整它以使用2D数组很容易-尽管字符串赋值需要
strcpy()
而不是
=
操作符。例如类似的东西<代码>strcpy(c、fgetc(fp)),尽管上面的一些评论给了我很大帮助,我用与M.M建议的方法类似的方法解决了我的问题@Pet3rMatta是一个优雅的答案,并教会了我calloc;)谢谢
// create an array of strings
char ** array = (char **)calloc(LINES, sizeof(char *));

for (size_t i = 0; i < LINES; i++) {
    // allocate space for each string
    array[i] = (char *)calloc(1, BUFSIZ);
    // get the input
    fgets(array[i], BUFSIZ, stdin);
    // remove the '\n' character
    // from the end of the string
    array[i][strlen(array[i]) - 1] = '\0';
}