【问题标题】:How can i make a struct keep the value ive assigned through the function?如何使结构保持通过函数分配的值?
【发布时间】:2021-03-25 12:07:03
【问题描述】:

基本上我试图通过函数为结构分配一个值,这样我分配的值在 main() 之后是相同的。

结构

struct member{
  char name;
  int age;
}m1;


void assigntostruct(struct member str,int age){

str.age = age;


main(){
int age=10;
assigntostruct(m1,age);
printf("%d",age);

}

我试过这样,值“age”被传递给str.age,但是当我printf它返回0。

【问题讨论】:

  • 您至少缺少assigntostruct 的右大括号。你能发布至少可以编译的代码吗?
  • 不需要将m1传递给函数,因为它是在全局范围内声明的,它已经可以从assigntostruct()访问,只需使用m1.age = age;就可以了。跨度>

标签: c struct pass-by-reference function-declaration


【解决方案1】:

你需要通过引用传递结构类型的对象。

在 C 中,通过引用传递一词意味着通过指向它的指针间接传递一个对象。

所以函数看起来像

void assigntostruct( struct member *str, int age){
    str->age = age;
    //...
}

并且可以这样称呼

assigntostruct( &m1, age );
printf("%d", m1.age);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2019-08-22
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多