2014-11-06 43 views
0
#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; 

} 

我正試圖編寫一個程序來獲取用戶的x和y座標,並將它們打印到屏幕上。一旦我輸入x和y座標並出去將它們打印到屏幕上,我會得到:(x,y)=(56,0)。我對結構工作很陌生,所以任何幫助都很好。謝謝。傳遞結構在C中運行

+1

您需要通過引用傳遞結構或將指針傳遞給它。此刻,當您將其發送到get和put函數時,您正在複製整個結構。 – RohinNZ 2014-11-06 23:01:53

回答

1
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); 
} 
+0

非常感謝。 – Module 2014-11-06 23:03:52

+1

添加一個解釋,爲什麼他的方法沒有工作,你的做法會使這是一個更有用的答案。 – 2014-11-06 23:05:49

+0

由於結構也通過值傳遞給函數,所以函數接收它是副本。你想返回一個爲此更新的結構,或者你需要接收一個指針。 – BLUEPIXY 2014-11-06 23:21:00

2

您也可以直接從get函數返回結構,因爲這是一個小結構。

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; 
} 
0

你必須使用指針,否則在get功能的點是點的main功能的副本。

#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; 
}