指向未知或不完整结构的指针 [英] Pointer to unknown or incomplete struct
问题描述
此问题是我知道这不是一个有用的程序,请弃权说您没有定义这个".讨论的主题是不透明类型的指针语法.很抱歉打扰太多人了,但无论如何答案都是有用的.
I know that it is not a useful program, please abstain to say "you didn't define this and that". The discussion was about pointer aritmethic on an opaque type. Sorry for bothering too many people, but the answers can be useful anyway.
该程序:
struct st1 {
int a,b;
};
struct st2;
typedef struct st2 *foo;
typedef struct foo *bar;
void main(void) {
struct st1 *net=0;
foo ft1=0;
bar test=0;
net++;
ft1++;
test++;
}
使用gcc编译时,会显示以下内容:
when compiled with gcc gives the following:
pc:~$ cc tmp2.c
tmp2.c: In function 'main':
tmp2.c:17:6: error: increment of pointer to unknown structure
ft1++;
^
tmp2.c:17:3: error: arithmetic on pointer to an incomplete type
ft1++;
^
tmp2.c:18:7: error: increment of pointer to unknown structure
test++;
^
tmp2.c:18:3: error: arithmetic on pointer to an incomplete type
test++;
^
我想更好地了解这里发生的情况,因为当不知道指针指向什么时,指针阿利通法有点困难...
I would like to understand better what is happening here, because of course pointer aritmethic is a bit difficult when not knowing what the pointer points to...
推荐答案
您已通过声明编译器来告知编译器您在程序中有一个struct st2
,但当时并没有定义它.这种承诺向编译器保证了其定义将在以后出现.
You have informed the compiler that you have a struct st2
in the program by declaring it, but have not defined it then and there. That sort of promised the compiler that its definition will appear later.
但是您还没有在任何地方定义它.
However you have not defined it anywhere.
在此处此处在声明和定义之间.
Read here about the difference between a declaration and definition.
按照函数原型的思路进行思考.
Think along the lines of a function prototype.
喜欢
void fun(int);
您说函数fun
返回void
并使用int
位于某处.而且,如果您未在程序中调用此函数,则不会造成任何危害.
You say a function fun
returning void
and taking an int
is located somewhere. And if you don't call this function in your program, no harm is done.
但是,如果要调用它,则必须在某个地方定义它,例如
But if you do call it, you must have it defined somewhere, like
void fun(int a)
{ ... }
这里与struct
的情况类似.如果您没有使用类型为struct st2
(和struct foo
)的变量或其typedef
-ed名称,则不会有任何错误.
The case with struct
here is similar. Had you not used a variable of type struct st2
(and struct foo
) or its typedef
-ed names, there wouldn't have been any errors.
但是,如果您确实使用它们,则必须对其进行定义,以便编译器可以知道应该怎么做.
But if you do use them, they must be defined so the compiler can know what it should do.
这篇关于指向未知或不完整结构的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!