简体   繁体   中英

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:

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. 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.

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.

2) Just make sure you put your "typedef" AFTER (or, at least, as part of) your struct definition:

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.

You should use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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