AD1

Thursday, 19 January 2017

Swap structure values

Assume that you have a structure defined as follow 
struct two_integers {int n1;int n2;};
and this structure is initialized as follow
struct two_integers x={100,-100}; 
Write a C function that returns the same structure x but n1 and n2 are swapped

#include <stdio.h>
struct two_integers {int n1;int n2;};
void swap(struct two_integers *xp)// pass structure variable by reference
{
int t=xp->n1;
xp->n1=xp->n2;
xp->n2=t;
return;
}
int main()
{
struct two_integers x={100,-100};// n1=100 and n2=-100;
struct two_integers *xp=&x;
swap(xp);
printf("n1=%d\tn2=%d\n",x.n1,x.n2);
return 0;
}


No comments:

Post a Comment