error expected specifier-qualifier-list before
I tried to compile this example:
#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);
}
I got an error: error expected specifier-qualifier-lis开发者_如何学Got before 's_tr'. what does it mean? The example i got from: http://publications.gbdirect.co.uk/c_book/chapter9/introduction.html
On second reading, it looks like someone accidentally inserted an x
before the {
. The original probably had an anonymous struct:
struct { int a, b, c; } s_tr;
You can rewrite it with a typedef like:
typedef struct { int a, b, c; } newtype;
newtype s_tr;
Here's some code I used to refresh my memory, with the various ways to declare a struct in C (anonymous, tagged, and typed):
// 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"
This code is (as far as I can tell) incorrect. You need to add a typedef to struct x
if you want to refer to it as s_tr. Otherwise, s_tr doesn't really mean anything (and in my case, won't even compile).
typedef struct x{
int a, b, c;
}s_tr;
However, this is not required. You could refer to the struct as x, but you have to put the struct keyword in front of it. Like this:
distance = offsetof(struct x, c);
Try this.
#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);
}
Also, this question and answer from the C-FAQ might help your understanding:
Q: What's the difference between these two declarations?
struct x1 { ... };
typedef struct { ... } x2;
A: The first form declares a structure tag; the second declares a typedef. The main difference is that the second declaration is of a slightly more abstract type--its users don't necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it:
x2 b;
Structures declared with tags, on the other hand, must be defined with the
struct x1 a;
form. [footnote]
(It's also possible to play it both ways:
typedef struct x3 { ... } x3;
It's legal, if potentially obscure, to use the same name for both the tag and the typedef, since they live in separate namespaces. See question 1.29.)
offsetof()
requires a type for the first argument.
You passing it an object of type struct x
.
精彩评论