我正在尝试定义一个返回指向结构的指针的函数。我认为我正确地遵循了这一点,( Returning a struct pointer )但是当我尝试访问指针的成员时,我的代码不断提示此错误消息,“错误:取消引用指向不完整类型的指针”。
这是我的代码
#include <stdio.h>
#include <string.h>
#include <assert.h>
struct lnode
{
char* word;
int line;
int count;
struct lnode* nn; /* nn = next node */
};
struct lnode* newNode (char* word, int line)
{
struct lnode* newn = (struct lnode*) malloc(sizeof (struct lnode));
if (!newn)
return NULL;
strcpy (newn->word, word);
newn->line = line;
newn->count = 1;
newn->nn = NULL;
return newn;
}
int main()
{
char* p = "hello";
struct lnode* head = newNode (p, 5);
//the following lines are causing errors
assert (!strcmp (head->word, p));
assert (head->line == 5);
assert (head->count == 1);
assert (!head->nn);
return 0;
}
感谢您的帮助!
最佳答案
除了明显的问题(您错过了包含 stdlib.h
)之外,您处理字符串的方式也存在问题。
在 C 中,你(是的,你)必须管理用于字符串的所有内存。这包括成员word
指向的内存。
您的代码执行以下操作(删除一些绒毛后):
struct lnode* newn = malloc(...);
strcpy (newn->word, word);
此处,newn->word
未初始化,因此可能会崩溃。
您将需要分配内存来存储字符串,例如通过再次调用 malloc()
:
struct lnode* newn = malloc(...);
newn->word = malloc(strlen(word) + 1);
strcpy (newn->word, word);
关于c - 返回指向结构体的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14939954/