繁体   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?

我目前正在研究迷宫,到目前为止,我已经从文本文件中读取了迷宫并将其存储到一维指针中,但是,我正在尝试将其存储到二维指针数组中,但是我一直遇到细分错误。 另外,我的第二个问题是,使用二维指针数组有哪些优势? 我似乎不了解如何正确实施它们。 这是我第一次使用2-D指针,因此我并不擅长使用它,但是我想进行改进,以便将来可以更好地使用它。 非常感谢您的提前帮助:)

到目前为止,这是我所做的:

#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;

}

您已经动态分配了空间供fgets()读取,但是您随后传递了错误的大小作为大小。 除非您使用的是非常小的机器(例如,主内存少于8 MiB,是的,我的意思是兆字节malloc()否则没有理由使用malloc() )。

char readLine[4096];

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

或者,如果您坚持使用malloc() ,则在对fgets()的调用中将101指定为大小。

您正在32位系统上进行编译,因此sizeof(inputFile) == sizeof(FILE *)在您的系统上为4。 因此,每次调用fgets() ,输入中最多包含三个字符,并且为空。

暂无
暂无

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

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