【问题标题】:Passing structure to function in C将结构传递给 C 中的函数
【发布时间】:2015-01-03 15:23:50
【问题描述】:
#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)。我是使用结构的新手,所以任何帮助都会很好。谢谢。

【问题讨论】:

  • 您需要通过引用传递结构或传递指向它的指针。目前,当您将其发送到 get 和 put 函数时,您正在复制整个结构。

标签: c structure pass-by-value


【解决方案1】:

您必须使用指针,否则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;
}

【讨论】:

    【解决方案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;
    }
    

    【讨论】:

      【解决方案3】:
      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);
      }
      

      【讨论】:

      • 解释为什么他的方法行不通而你的方法行得通,这会是一个更有用的答案。
      • 由于结构体也是按值传递给函数的,所以函数接收到的就是副本。您想返回一个为此更新的结构,还是需要接收一个指针。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      相关资源
      最近更新 更多