简体   繁体   English

在处理2D指针时如何正确分配内存,以及使用2D指针数组有哪些优势?

[英]How to malloc properly when dealing with 2-D pointers and what are some of the advantanges of using a 2-D pointer array?

I am currently, working on solving a maze and so far I have read the maze from a text file and stored it into an 1-D pointer, however, I am trying to store it into a 2-D pointer array, but I keep getting a segmentation fault. 我目前正在研究迷宫,到目前为止,我已经从文本文件中读取了迷宫并将其存储到一维指针中,但是,我正在尝试将其存储到二维指针数组中,但是我一直遇到细分错误。 Also, my second question, what are some advantages of using a 2-D pointer array? 另外,我的第二个问题是,使用二维指针数组有哪些优势? I do not seem to understand how to properly implement them. 我似乎不了解如何正确实施它们。 This is my first time using 2-D pointers so I'm not as a great at it, however I would like to improve so I can become good at it in the future. 这是我第一次使用2-D指针,因此我并不擅长使用它,但是我想进行改进,以便将来可以更好地使用它。 Thank you so much for the help in advance :) 非常感谢您的提前帮助:)

Here is what I have done so far: 到目前为止,这是我所做的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mazegen.h"
#define  BUFFERSIZE 500

int main(int argc, char**argv)
{
    char*readFile;
    char**storeMaze;
    FILE*fp;
    int i;
    i=0;
    readFile = malloc(sizeof(char)*(BUFFERSIZE)+1);

    if(argc != 2)
    {
        printf("Error opening file, incorrect format. <programNam <inputfileName>\n");
        exit(0);
    }
    else
    {
        fp = fopen(argv[1], "r");

        if(fp == NULL)
        {
            printf("Empty File. Error. Exiting Program.\n");
            exit(0);
        }

        while(fgets(readFile,sizeof(readFile),fp) != NULL)
        {
            storeMaze = malloc(sizeof(char*)*(strlen(readFile)+1));
            strcpy(storeMaze[i], readFile);
        }
    }

   free(readFile);
   fclose(fp);
   return 0;

} }

You've dynamically allocated space for the fgets() to read into, but you then pass the wrong size as the size. 您已经动态分配了空间供fgets()读取,但是您随后传递了错误的大小作为大小。 There's no reason to use malloc() unless you're on an unusually small machine (say less than 8 MiB — yes, I mean megabytes — of main memory). 除非您使用的是非常小的机器(例如,主内存少于8 MiB,是的,我的意思是兆字节malloc()否则没有理由使用malloc() )。

char readLine[4096];

while (fgets(readLine, sizeof(readLine), inputFile) != NULL)

Or, if you insist on malloc() , specify 101 as the size in the call to fgets() . 或者,如果您坚持使用malloc() ,则在对fgets()的调用中将101指定为大小。

You're compiling on a 32-bit system so sizeof(inputFile) == sizeof(FILE *) which is 4 on your system. 您正在32位系统上进行编译,因此sizeof(inputFile) == sizeof(FILE *)在您的系统上为4。 Hence you got up to three characters and a null from the input for each call to fgets() . 因此,每次调用fgets() ,输入中最多包含三个字符,并且为空。

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

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