0

I have the following code:

#define MAX_VIDEOS 100

typedef struct video_t {
    int likes;
    int dislikes;
    char* title;
    user_t* uploader;
} video_t;

typedef struct user_t {
    char* username;
    char* password;
    video_t videos[MAX_VIDEOS];
} user_t;

I want to use user_t in video_t and vice versa.

In every case, gcc just says "unknown type name":

youtube.c:9:5: error: unknown type name ‘user_t’

user_t* uploader;
  ^

which is normal, but I can't think of a way to solve this problem.

Sourav Ghosh
  • 130,437
  • 16
  • 177
  • 247
wencakisa
  • 5,360
  • 2
  • 14
  • 34

4 Answers4

3

You need to forward-declare user_t:

#define MAX_VIDEOS 100

typedef struct user_t user_t;

typedef struct video_t {
    int likes;
    int dislikes;
    char* title;
    user_t* uploader;
} video_t;

typedef struct user_t {
    char* username;
    char* password;
    video_t videos[MAX_VIDEOS];
} user_t;
Vittorio Romeo
  • 86,944
  • 30
  • 238
  • 393
1

Forward declare the user_t type-alias:

typedef struct user_t user_t;

After that you can use user_t *uploader in the video_t structure.

Some programmer dude
  • 380,411
  • 33
  • 383
  • 585
1

Move the type definition for the missing type at the beginning. This makes sure compiler is aware of the type while it is being used.

Something like

 typedef struct user_t user_t;

and then, later, just declare the structure, the typedef is already there.

at the beginning of the shown snippet can solve the issue. In this way

  • While declaring struct video_t, user_t is already known and the typedef video_t is defined.
  • While declaring struct user_t, video_t is known.

So, both end meets.

Sourav Ghosh
  • 130,437
  • 16
  • 177
  • 247
1

The first struct doesn't know the signature of user_t (declare it forward)

Change to

#define MAX_VIDEOS 100

typedef struct user_t user_t;

typedef struct video_t {
    int likes;
    int dislikes;
    char* title;
    user_t* uploader;
} video_t;

struct user_t {
    char* username;
    char* password;
    video_t videos[MAX_VIDEOS];
};
David Ranieri
  • 37,819
  • 6
  • 48
  • 88