简体   繁体   English

在C中取消引用指向不完整类型错误的指针

[英]Dereferencing pointer to incomplete type error in C

I bumped into this error when I was trying to access a field in my defined struct: 当我尝试访问我定义的结构中的字段时,我遇到了这个错误:

struct linkNode{
    struct linkNode *next;
    char *value;
};

In the header file I defined a type called linkNode_t: 在头文件中,我定义了一个名为linkNode_t的类型:

typedef struct linkNode linkNode_t;

When I tried to use this struct in the main of another file, everything else was fine except when I tried to do 当我试图在另一个文件的主要部分中使用这个结构时,其他一切都很好,除非我试图这样做

linkNode_t* currentpath = /*a pointer to a struct of type linkNode_t*/
int something = strlen(currentpath->value);/****ERROR*****/

Compiler gave me the incomplete type error. 编译器给了我不完整的类型错误。 Am I declaring the struct properly? 我是否正确地宣布了结构?

Struct has to be declared in header, before you do typedef. 在执行typedef之前,必须在头文件中声明Struct。 You can combine both: 你可以把两者结合起来

typedef struct linkNode {
    struct linkNode *next;
    char *value;
} linkNode_t;

As the others pointed out, it's generally better to put your "typedef" and your struct definition all in the same place. 正如其他人所指出的那样,将“typedef”和结构定义全部放在同一个地方通常会更好。

But that isn't required, and that's not the problem. 但这不是必需的,这不是问题。

This test case compiles and runs correctly: 此测试用例编译并正确运行:

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

#define NULL 0

struct linkNode{
    struct linkNode *next;
    char *value;
};

typedef struct linkNode linkNode_t;

linkNode_t rec = {
  NULL,
  "abcdef"
};

int
main (int argc, char *argv[])
{

  linkNode_t* currentpath = &rec;
  int something = strlen(currentpath->value);
  printf ("sizeof (rec)= %d, currentpath->value= %s, something= %d...\n", 
    sizeof (rec), currentpath->value, something);
  return 0;
}

ACTUAL PROBLEM AND SOLUTION: 实际问题和解决方案:

1) You're doing all the right stuff. 1)你正在做所有正确的事情。

2) Just make sure you put your "typedef" AFTER (or, at least, as part of) your struct definition: 2)确保在结构定义之后 (或者至少作为其一部分)放置“typedef”:

struct linkNode{
...
};

typedef struct linkNode linkNode_t;
struct linkNode{
    struct linkNode *next;
    char *value;
};

This is incomplete because you cannot use struct directly inside the structure. 这是不完整的,因为您不能直接在结构中使用struct。

You should use 你应该用

typedef struct linkNode{
    struct linkNode *next;
    char *value;
}new_name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM