简体   繁体   English

将字符加载到动态分配的2D数组中

[英]Loading chars into dynamically allocated 2D array

This might be one of the common questions, but all solutions I've seen so far are not working. 这可能是常见问题之一,但到目前为止我看到的所有解决方案都无效。 I want to dynamically allocate 2D array of chars. 我想动态分配二维数组的字符。 I get these chars from a .txt file. 我从.txt文件中获取这些字符。 I even have set number of rows (int r) and columns (int s). 我甚至设置了行数(int r)和列(int s)。 Allocation itself is working but whenever I try to load chars from a file into this array, it crashes. 分配本身是有效的,但每当我尝试将文件中的字符加载到此数组中时,它就会崩溃。 Have no idea why. 不知道为什么。

File is ordered in this way: 文件以这种方式订购:

Here is the code: 这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{

Opening desired file: 打开所需文件:

    FILE* file;
    file = fopen(argv[1], "r");
    if (file == NULL) {
        printf("Error occurred when loading the file, program quits now.");
        return 1;
    } else {
    printf("File loaded successfully.");
    }

Getting info about number of columns and rows (r are rows, s are columns): 获取有关列数和行数的信息(r是行,s是列):

    int r,s,i,j;
    char arrayInfo[6];
    fgets (arrayInfo, 6, file);
    char* comma = strchr(arrayInfo, ',');
    s = atoi(comma - 1)+1;
    r = atoi(comma + 1);

Memory allocation for a 2D array of chars: 二维chars数组的内存分配:

    char **array = malloc(r * sizeof(char *));
    for(i=0;i<r;i++){
        array[i] = malloc(s * sizeof(char));
    }

NOT WORKING Loading of chars from a file and then printing them. 不工作从文件中加载字符然后打印它们。 This code would work with "char array [r][s];" 这段代码适用于“char array [r] [s];” instead of dynamic allocation. 而不是动态分配。

    for (j=0;j<r;j++) {
        for (i=0;i<s;i++) {
            array[i][j] = fgetc (file);
        }
    }

    for (j=0;j<r;j++) {
        for (i=0;i<s;i++) {
            printf ("%c",array[i][j]);
        }
    }
    return 0;
}

If there is a crash I doubt that issue is with: 如果发生崩溃我怀疑这个问题是:

array[i] = malloc(s * sizeof(char));

Please make sure whether malloc() succeeded or not first, later try to write to this allocated memory. 请确保malloc()是否成功,稍后再尝试写入此分配的内存。

a[i][j] i is your row and j is your column. a[i][j] i是你的行, j是你的专栏。 We see in your code it is interchanged. 我们在你的代码中看到它是互换的。

I don't know how your file looks like but please re-check the below evaluation 我不知道您的文件是什么样的,但请重新检查以下评估

s = atoi(comma - 1)+1; /* comma is a pointer and you are decrementing it by 1? */

, is being used in strchr and later the pointer is decremented by 1 to get the integer value which is not what you want. ,正在strchr中使用,稍后指针递减1得到不是你想要的整数值。 Fix this also. 解决这个问题。

感谢您输入的人 - array [i] [j]需要更改为array [j] [i],然后它可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM