[英]Issue allocating memory for dynamic array of structs in C
我正在嘗試為結構數組動態分配 memory
我將命令行中給出的文件的輸入掃描到一個結構中,該結構包含有關文件中每個 url 的 position 的信息。
file1.txt
url4
url3
url2
url1
url5
file2.txt
url3
url2
url1
url4
typedef struct url {
char *url; // url
int pos; // position in original file
} URL;
int main(int argc, char *argv[]) {
//Error when no file in given in commandline
if (argc < 2) {
fprintf(stderr, "Usage: %s rankA.txt rankD.txt", argv[0]);
exit(1);
}
URL *urlArray = NULL;
char url[1000];
for (int i = 0; i < argc - 1; i++) {
FILE *fp = fopen(argv[i + 1], "r");
int numURLs = 0;
while (fscanf(fp, "%s", url) != EOF) {
urlArray = realloc(urlArray, (numURLs + 1) * sizeof(struct url));
urlArray[i].url = malloc(strlen(url) + 1);
strcpy(urlArray[numURLs++].url, url);
urlArray->pos = numURLs;
}
fclose(fp);
}
return 0;
}
當我運行此代碼時,出現“SEGV on unknown address”錯誤。 我知道在分配 memory 時我在某處出錯了,我只是不知道在哪里。 我將如何解決這個問題?
urlArray = realloc(urlArray, (numURLs + 1) * sizeof(struct url));
urlArray[i].url = malloc(strlen(url) + 1);
當您應該使用 numURLs 時,您卻使用了變量 i。 i 是循環變量,這就是為什么你在每個地方都得到相同的 URL 的原因。
將這些行更改為此,它應該可以工作:
urlArray = realloc(urlArray, (numURLs + 1) * sizeof(struct url));
urlArray[numURLs].url = malloc(strlen(url) + 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.