【问题标题】:Passing Struct members in Functions在函数中传递结构成员
【发布时间】:2014-03-26 18:11:53
【问题描述】:

我想在 function 中传递 struct 成员。我不是那个意思:

struct smth
{
  int n;
};

void funct(struct smth s);

我想要这些结构

struct student {
char name[50];
int semester;
};

struct prof {
char name[50];
char course[50];
};

struct student_or_prof {
  int flag;
  int size;
  int head;
   union {
     struct student student;
     struct prof prof;
   }
}exp1;
struct student_or_prof *stack;
struct student_or_prof exp2;

用变量而不是结构变量在函数中传递它们的成员

int pop(int head,int n)
{
 if(head==n)
  return 1;
 else head++;
}

因为我不想只将函数用于结构。有可能吗?

编辑我希望数字也改变,而不是返回,类似于指针。

EDIT_2我也知道这个 pop(exp1.head,n) 可以工作,但我也希望 exp1.head 在函数 pop 结束后改变。

【问题讨论】:

  • 你可以传递struct变量的地址并使用它。除了指针,你还需要其他方法吗?
  • 我想要所有可能的方式,但我也想要我发送给函数的结构成员的数量也改变这就是我提到指针的原因

标签: c function struct


【解决方案1】:

使用指针。将指针传递给 exp1.head 并通过在函数中取消引用来操作它,

int pop(int * head,int n)
{
 if(*head==n)
  return 1;
 else (*head)++;
}

调用函数为,

pop(&exp1.head,n);

【讨论】:

  • 是的!正是我想要的
【解决方案2】:

首先,您在struct student_or_prof 内的union 定义之后缺少一个分号。

根据您的编辑#2,您应该传递变量的地址,将其作为函数指向变量的指针,然后编辑/递增地址的内容(指针指向的变量) .像下面这样:

#include <stdio.h>

struct student_or_prof {
    int head;
} exp1;

int pop( int * head, int n ) {
    if ( *head == n )
        return 1;
    else (*head)++;
}

int main( ){

    int returnval;

    exp1.head = 5;
    returnval = pop( &exp1.head, 10 );
    printf( "%d", exp1.head );

    getchar( );
    return 0;
}

这将打印6。在这里,我传递exp1.head的地址,这样pop函数就可以引用你手中的实际exp1.head。否则,pop 将只被告知exp1.head 拥有的值,将该值复制到它自己的head 变量中,然后玩弄。

而且,无论如何,从pop 返回一些int 是明智的。现在它仅在满足*head == n 时返回一个值,并返回一些没有意义的东西。我不认为你会想要那个,所以:

...
else {
    (*head)++;
    return 0;
}
...

会更好。

如果您不喜欢 *head 周围的括号,那么您可能希望使用 ... += 1; 而不是后缀增量,后者的优先级低于取消引用运算符 *

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    • 2021-03-03
    • 2022-11-21
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    相关资源
    最近更新 更多