在函数中传递Struct成员

时间:2014-03-26 18:11:53

标签: c function struct

我想在函数中传递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)可以正常工作,但我也想在函数pop结束后更改exp1.head。

2 个答案:

答案 0 :(得分:3)

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

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

调用函数as,

pop(&exp1.head,n);

答案 1 :(得分:2)

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

根据您的编辑#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变量中,然后使用该值。

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

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

会更好。

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