c - 有没有办法在函数中使用 typedef 结构变量...?

标签 c struct typedef

如果我在 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(在 mainfunction 的主体之外):

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
}

否则,boofunction 不可见。

编辑

正如 user3386109 指出的,typedef 在这里并不相关 - 无论 boo 如何声明,或者是否使用 声明,答案都是相同的>typedef 名称与否。

关于c - 有没有办法在函数中使用 typedef 结构变量...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57514092/

相关文章:

c 在结构体中使用枚举

c - 为什么在将 malloc() 指针分配给 char* 时出现段错误?

将结构转换为成员类型的指针

c++ - 在运行时有条件地定义 3 个类中的哪一个将在其余 C++ 代码中使用

任何人都可以帮助我理解这个程序中的 typedef 吗?

c - 以下代码如何将输出作为 -99?

c - 无法将二进制文件中的数据读入结构指针数组

c - 没有语法错误吗?应该 printf ("one" ", two and " "%s.\n", "three");是有效代码?

c - 数组中的元素数量是否可能超过编译时定义的数组大小?

c - typedef 的重新定义