Home > Software engineering >  Visual studio not accepting my typedef struct
Visual studio not accepting my typedef struct

Time:03-16

I'm working on a class exercise (in c) using calloc pointers with a typedef struct, the problem is that visual studio is not recognizing the variable I wrote.

typedef struct {
    int id;
    dog* next;
}dog;

my main code is correct but since the typedef struct is not working I end up with 35 plus errors

dog* initdog(int a_id);
void AfficherChien(dog* a_element);

void main() {
    dog* first = NULL;
    dog* temp = NULL;
    first = (dog*)calloc(1, sizeof(dog));
    for (int i = 0; i < 5; i  ) {
        if (i == 0) {
            first = initdog(i);
            temp = first;
        }
        else
        {
            temp->next = initdog(i);
            temp = temp->next;
        }

    }
}

dog* initdog(int a_id) {
    dog* elem = (dog*)calloc(1, sizeof(dog));
    elem->id = a_id;
    return elem;
}

void AfficherChien(dog* a_element)
{
    if (a_element->next != NULL)
    {
        AfficherChien(a_element->next);
    }
    printf("voici l'id du chien: %d\n", a_element);
} 

enter image description here

CodePudding user response:

The struct is not a complete type before it reaches the semicolon in }dog;. Until that point the compiler has no idea what dog is, so you can't use it inside the struct.

The normal solution is to use a struct tag as placeholder:

typedef struct woof {
    int id;
    struct woof* next;
}dog;

After which you can forget all about "struct woof" in your code and refer to next as type dog*.

Alternatively you could forward declare the type:

typedef struct dog dog;

struct dog {
    int id;
    dog* next;
};

CodePudding user response:

The struct definition

typedef struct {
    int id;
    dog* next;
}dog;

needs to be

typedef struct dog {
    int id;
    struct dog *next;
} dog;

because the type definition of dog hasn't yet been made.

  •  Tags:  
  • c
  • Related