c - 返回指向结构体的指针

标签 c

我正在尝试定义一个返回指向结构的指针的函数。我认为我正确地遵循了这一点,( 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/

相关文章:

c - 将两个以上的 "struct"写入文件的问题,然后读取文件

c - 在 Unix 中获取 errno EACCES

python - 用十进制数 64165 位的 `n ** n` 计算 `n`(n 乘以 n)需要多长时间?

c - 什么时候用箭头,什么时候用点?

常见的误解 : Files have an EOF char at their end

c - 我的未分配指针将指向这里什么?

c - 如何在同一台机器上以编程方式获取通过AF_INET套接字连接到我的代理的进程的PID?

c - 为什么初始化的变量在注释行后不可见?

c++ - Pre Z 缓冲区通过 OpenGL?

c - 当您在 C 中将两种不同的类型相加时会发生什么?