簡體   English   中英

為什么我的用於將元素插入到哈希樹中的C代碼在Main()中起作用,但是當我通過函數調用它時卻不起作用?

[英]Why does my C code for inserting an element into a hash tree work in Main() but not when I call it via function?

我相當確定這與指針和使用副本的函數有關,但是我不確定如何...因為我已經將指針作為create()的參數插入了;

#include <stdio.h>
#include <cs50.h> 
#include <string.h>

typedef struct list {
    string word;
    struct list *next;
}
linkedList; 

struct list* create (string newWord) {
    linkedList *new = malloc(sizeof(newWord));
    new->word = newWord;
    new->next = NULL;
    return new;
}

struct list* insert (struct list *theList, string newValue) {
    linkedList *anotherOne = create(newValue);
    anotherOne->next = theList;
    return anotherOne;
}

int hash (string name) {
    return strlen(name);
}

void hashInsert (struct list *theList, string newValue) {
    theList = create(newValue);
    }

int main(void) {
   linkedList *names[24] = {NULL};
   int num = hash("heey");
 //  names[num] = create("heey"); // <- this code works when I uncomment it
   hashInsert(names[num], "heey"); // <-- this causes a segfault.. idk why
   printf("%s", names[num]->word);
}

您的hashInsert函數創建指針的本地副本( theList ),您修改了該本地副本,但是main函數中的實際指針仍設置為NULL 對此調用printf是導致分段錯誤的原因。

您可以通過將指針傳遞給函數的指針來解決此問題

void hashInsert(string list **theList, string newValue) {
    *theList = create(newValue);
}

然后叫它

hashInsert(&names[num], "heey");

這樣,您可以從main修改指針的值。

編輯

同樣,作為注釋狀態,您的malloc確實沒有分配足夠的內存,您還需要一些內存來存儲下一個列表指針。

問題出在您的hashInsert函數上。 它按值獲取指針(因此您傳遞的原始指針不會被修改)。 有更好的方法可以解決這個問題-

struct list* hashInsert(char* string){
    return create(string);
}

除此之外,請不要使用string ,而應始終使用char*因為這實際上是什么。 我看到您正在使用某些庫,但是最好自己自己包括適當的標頭,在這種情況下,您應該包括stdlib.h因為它包含malloc()的定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM