[英]Passing Struct members in Functions
我想在函数中传递结构成员。 我的意思不是这样的:
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结束后进行更改。
使用指针。 将poniter传递给exp1.head并通过在函数中取消引用它来对其进行操作,
int pop(int * head,int n)
{
if(*head==n)
return 1;
else (*head)++;
}
调用函数为
pop(&exp1.head,n);
首先,在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
的值, exp1.head
将该值复制到其自己的head
变量中,然后进行操作。
而且,在任何情况下都应该从pop
中返回一些int
是明智的。 现在,仅当满足*head == n
时,它才返回一个值,并返回没有意义的值。 我认为您不想要这样,所以:
...
else {
(*head)++;
return 0;
}
...
会更好。
如果您不喜欢*head
周围的括号,那么您可能要使用... += 1;
而不是后缀增量,后者比解引用运算符*
优先级低。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.