Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

struct in C: Error storage size of 'params' isn't known

I'm a bit new to C and I'm having a bit of trouble with a project I'm currently working on. Essentially I have the following files: main.c, alarm.c, alarm.h

I have a struct declaration in alarm.c that looks like:

#define STRLEN 150;

struct alarmparams
{
    char time[STRLEN];
    char duration[STRLEN];
    char snooze[STRLEN];
    char port[STRLEN];
};

In main.c I have:

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

int main(int argc, char *argv[])
{   
    struct alarmparams params;

    printf("%s, %s
", params.time, params.duration);
}

And in alarm.h I have:

struct alarmparams;

Right now when I go to compile I get the following error:

error: storage size of ‘params’ isn’t known

I've looked through other posts regarding this error, so I have done a bit of research on this already. I've also tried some of the suggested solutions and it's either I get the exact same error or I got more on top of it. I'm at a lose as to how to fix this.

Is there something I'm missing? Did I declare something incorrectly?

In general should structs be declared in the header file or the c file? Or does it even matter? What's the different between:

struct foo {...};

and

typedef struct foo {...};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
struct alarmparams;

is the declaration of an incomplete type. You can create a pointer to an object of this type but you cannot declare an object of this type or take its size until it has been completed. You have to make its complete declaration visible in main.c to declare an object of its type.

If you use the type in both alarm.c and main.c, just declare it in alarm.h and include alarm.h in main.c.

For you second question, the difference between:

struct foo {...};

and

typedef struct foo {...} foo_;

is in the latter case you also declare an alias foo_ for the type name struct foo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...