[英]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.