Reputation: 1399
I want to pass struct members in function . I don't mean something like that:
struct smth
{
int n;
};
void funct(struct smth s);
I want these structs
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;
To pass their members in a fucntion with variables not struct variables
int pop(int head,int n)
{
if(head==n)
return 1;
else head++;
}
Because i don't want to use the function for structs only. Is it possible?
EDIT I want the numbers also to change , not return , something like pointer.
EDIT_2 Also i know that this pop(exp1.head,n) it works, but i want also the exp1.head to change after the end of the function pop.
Upvotes: 1
Views: 15884
Reputation: 3069
First things first, you are missing a semicolon, after the union
definition inside the struct student_or_prof
.
As per your edit #2, you should be passing the address of the variable, taking it as a pointer to a variable by the function, and then editing/incrementing the content of the address (the variable that pointer points to). Like the following:
#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;
}
This will print a 6
. Here, I am passing the address of the exp1.head
, so that the function pop
can refer to the actual exp1.head
you have in your hands. Otherwise, the pop
will be only informed about the value that exp1.head
had, copy that value into its own head
variable, play around with that.
And also, it would be sensible to return some int
from the pop
in any case. Right now it returns a value only when *head == n
is satisfied, and returns something that wouldn't make sense. I don't think you'd want that, so:
...
else {
(*head)++;
return 0;
}
...
Would be better.
If you don't like the parenthesis around the *head
, then you may want to use ... += 1;
instead of a postfix increment, which has less precedence over the dereferencing operator *
.
Upvotes: 3
Reputation: 3162
Use pointers. pass poniter to exp1.head and manipulate it by dereferencing it in function as,
int pop(int * head,int n)
{
if(*head==n)
return 1;
else (*head)++;
}
call function as,
pop(&exp1.head,n);
Upvotes: 4