Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing a struct into a function 1

Status
Not open for further replies.

countdrak

Programmer
Jun 20, 2003
358
US
I am trying to pass a whole struct into a function. I don't even know if thats possible in C. This code compiles, but doesn't work. Any suggestions?

Code:
#include <stdio.h>
#include <stdlib.h>

int UpdateThreshold(peak);

struct peak
{
	double	val[2];
	double	status[2];
	double	temp_val[2];
} Peak;



int main()
{
	
	struct peak x;
	x.val[1] = 3;
	UpdateThreshold(x);
	return 0;
}

int UpdateThreshold(struct peak v)
{
	printf("x val is %d\t", v.val[1] );
	return 0;
}

Thanks in advance.
 
Ya, Im stupid, trying to print a double value by using %d. How stupid! Sorry guys....
 
There are two ways of passing a struct:

1) by value
2) by pointer

The method you're using is by value. The difference is that

1) by value copies the entire structure into the stack. Any values modified in the function will not be copied back to the original.
Code:
int UpdateThreshold (struct peak v)
{
   v.val[1] = 10;
}

main ()
{
   struct peak vvv;
   vvv.val[1] = 20.0;
   UpdateThreshold (vvv);
   printf ("%f\n", vvv.val[1]);
   return 0;
}
will print 20
2) by pointer copies a pointer to the structure into the stack. You need to dereference the pointer to access the values and whatever you do to the structure you will be doing to the original.
Code:
int UpdateThreshold (struct peak* v)
{
   v->val[1] = 10.0;
}

main ()
{
   struct peak vvv;
   vvv.val[1] = 20;
   UpdateThreshold (&vvv);
   printf ("%f\n", vvv.val[1]);
   return 0;
}
will print 10
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top