如果我在 main 中声明了 typedef 结构变量而不将其作为参数传递,有没有办法在函数中使用它?
typedef struct {
/* .... */
}a;
int main(){
a boo;
char string[40];
function(string);
}
void function(char string[]){
/* can I use the boo struct here in the function? */
}
最佳答案
由于问题中的代码当前已编写,所以function
无法访问变量boo
。
您需要将指向 boo
的指针作为参数传递给 function
:
int main( void )
{
...
function( string, &boo );
...
}
void function( char *str, a *b )
{
...
}
或者您需要在文件范围内声明 boo
(在 main
或 function
的主体之外):
a boo;
int main( void )
{
...
function( string );
...
}
void function( char *str )
{
// do something with str and boo
}
或者,将全局指针设置为指向 boo
:
a *ptr;
int main( void )
{
...
ptr = &boo;
...
function( string );
...
}
void function( char *str )
{
// do something with str and *ptr
}
否则,boo
对function
不可见。
编辑
正如 user3386109 指出的,typedef
在这里并不相关 - 无论 boo
如何声明,或者是否使用 声明,答案都是相同的>typedef
名称与否。
关于c - 有没有办法在函数中使用 typedef 结构变量...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57514092/