[英]Why does my C code for inserting an element into a hash tree work in Main() but not when I call it via function?
I'm fairly certain this has something to do with pointers and the function using copies instead, but I'm not sure how...because I've inserted the pointer as a parameter for create(); 我相当确定这与指针和使用副本的函数有关,但是我不确定如何...因为我已经将指针作为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);
}
Your hashInsert
function creates a local copy of the pointer ( theList
), you modify said local copy, but the actual pointer in your main
function is still set to NULL
. 您的hashInsert
函数创建指针的本地副本( theList
),您修改了该本地副本,但是main
函数中的实际指针仍设置为NULL
。 Calling printf
on that is the cause of your segmentation fault. 对此调用printf
是导致分段错误的原因。
You can resolve this issue by passing a pointer to the pointer to your function 您可以通过将指针传递给函数的指针来解决此问题
void hashInsert(string list **theList, string newValue) {
*theList = create(newValue);
}
and then call it 然后叫它
hashInsert(&names[num], "heey");
This way, you modify the value of the pointer from main
. 这样,您可以从main
修改指针的值。
EDIT 编辑
Also, as the comments state, your malloc
does indeed not allocate enough memory, you also need some memory to store the next list pointer. 同样,作为注释状态,您的malloc
确实没有分配足够的内存,您还需要一些内存来存储下一个列表指针。
The problem is with you hashInsert
function. 问题出在您的hashInsert
函数上。 It takes the pointer by value (so the original pointer you pass isn't modified). 它按值获取指针(因此您传递的原始指针不会被修改)。 There's a much better way to go about this- 有更好的方法可以解决这个问题-
struct list* hashInsert(char* string){
return create(string);
}
A few points aside from that, don't use string
, always use char*
since that what it really is. 除此之外,请不要使用string
,而应始终使用char*
因为这实际上是什么。 I see you're using some library, but you're better off simply including the proper headers yourself, in this case, you should include stdlib.h
since it contains the definition of malloc()
. 我看到您正在使用某些库,但是最好自己自己包括适当的标头,在这种情况下,您应该包括stdlib.h
因为它包含malloc()
的定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.