Reputation: 250
#include<stdio.h>
#include<stdlib.h>
struct point
{
int x;
int y;
};
void get(struct point p)
{
printf("Enter the x and y coordinates of your point: ");
scanf("%d %d",&p.x,&p.y);
}
void put(struct point p)
{
printf("(x,y)=(%d,%d)\n",p.x,p.y);
}
int main ()
{
struct point pt;
get(pt);
put(pt);
return 0;
}
I am trying to write a program to get the x and y coordinates from the user and them print them out to the screen. Once I enter the x and y coordinates and go out to print them out to the screen I get: (x,y)=(56,0). I am new to working with structures so any help would be good. Thank you.
Upvotes: 0
Views: 143
Reputation: 679
You had to use pointers, otherwise the point in the get
function is a copy of the point in main
function.
#include<stdio.h>
#include<stdlib.h>
typedef struct point
{
int x;
int y;
} Point;
void get(Point *p)
{
printf("Enter the x and y coordinates of your point: ");
scanf("%d %d",&p->x,&p->y);
}
void put(Point *p)
{
printf("(x,y)=(%d,%d)\n",p->x,p->y);
}
int main ()
{
Point pt;
get(&pt);
put(&pt);
return 0;
}
Upvotes: 0
Reputation: 74
You may also return the structure directly from get function, since this is a small structure.
struct point get()
{
struct point p;
printf("Enter the x and y coordinates of your point: ");
scanf("%d %d",&p.x,&p.y);
return p;
}
int main ()
{
put(get());
return 0;
}
Upvotes: 2
Reputation: 40145
void get(struct point *p)// get(&pt); call from main
{
printf("Enter the x and y coordinates of your point: ");
scanf("%d %d",&p->x,&p->y);
}
Upvotes: 1