简体   繁体   中英

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. 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. 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).

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() .

You're compiling on a 32-bit system so sizeof(inputFile) == sizeof(FILE *) which is 4 on your system. Hence you got up to three characters and a null from the input for each call to fgets() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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