错误预期说明符 - 限定符 - 列表之前

时间:2009-11-08 08:48:00

标签: c

我试图编译这个例子:

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

main(){
    size_t distance;

    struct x{
        int a, b, c;
    } s_tr;

    distance = offsetof(s_tr, c);

    printf("Offset of x.c is %lu bytes\n", (unsigned long)distance);

    exit(EXIT_SUCCESS); 
}

我收到了一个错误:'s_tr'之前的错误预期说明符 - 限定符列表。这是什么意思?我得到的例子是:http://publications.gbdirect.co.uk/c_book/chapter9/introduction.html

4 个答案:

答案 0 :(得分:1)

在第二次阅读时,看起来有人在x之前意外插入{。原文可能有一个匿名结构:

struct { int a, b, c; } s_tr;

您可以使用typedef重写它:

typedef struct { int a, b, c; } newtype;
newtype s_tr;

以下是我用来刷新内存的一些代码,以及在C语言中声明结构的各种方法(匿名,标记和键入):

// Anonymous struct
struct { int a,b; } mystruct1;

// Tagged struct
struct tag1 { int a,b; };
struct tag1 mystruct2; // The "struct" is not optional

// Typedef declaring both tag and new type
typedef struct tag2 { int a, b; } type1;
struct tag2 mystruct3;
type1 mystruct4; // Unlike tags, types can be used without "struct"

答案 1 :(得分:0)

此代码(据我所知)不正确。如果要将typedef称为s_tr,则需要将typedef添加到struct x。否则,s_tr实际上并不意味着什么(在我的情况下,甚至不会编译)。

 typedef struct x{
     int a, b, c;
 }s_tr;

但是,这不是必需的。您可以将结构称为x,但您必须将struct关键字放在它前面。像这样:

distance = offsetof(struct x, c);

答案 2 :(得分:0)

试试这个。

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

typedef struct { int a, b, c; } s_tr;

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

    size_t distance; 

    distance = offsetof(s_tr, c);
    printf("Offset of x.c is %lu bytes\n",
                (unsigned long)distance);

    exit(EXIT_SUCCESS); 
}

另外,this question and answer from the C-FAQ might help your understanding

问:这两个声明有什么区别?

struct x1 { ... };
typedef struct { ... } x2;

答:第一个表单声明了一个结构标记;第二个声明了一个typedef。主要区别在于第二个声明是一个稍微抽象的类型 - 它的用户不一定知道它是一个结构,并且在声明它的实例时不使用关键字struct:

x2 b;

另一方面,用标签声明的结构必须用

定义
struct x1 a;

形式。 [脚注]

(也可以双向播放:

typedef struct x3 { ... } x3;

对于标记和typedef使用相同的名称是合法的,如果可能不明确,因为它们位于不同的名称空间中。见问题1.29。)

答案 3 :(得分:0)

offsetof()第一个参数需要类型 您传递了struct x类型的对象

相关问题