指针从函数到函数的传递

问题描述 投票:0回答:1

我有一个问题,因为在从控制台加载数据时,弹出了一个错误,我认为将指标传递给函数是一件棘手的事情,但我不知道如何解决。

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

typedef struct rn{
    int n;   /**numerator**/
    unsigned d;    /**denomirator**/
} rationalNumber;

typedef struct dot{
    rationalNumber x;
    rationalNumber y;
} point;

int gcd(int a, int b)
{
  if(b!=0)
    return gcd(b,a%b);

       return a;
}

void input(rationalNumber *a)
{
    int nwd;
    if (scanf("%d/%u",&(a->n), &(a->d)) == 1) a->d=1;
    else
    {
        nwd = abs(gcd(a->n, a->d));
        a->n = a->n/nwd;
        a->d = a->d/nwd;
    }


}

void load_point(point *a, void(*function)(rationalNumber *))
{
    function(&a->x);
    function(&a->y);

}

int main(void)
{

    rationalNumber *z;
    point *a;


    load_point(a, input);



return 0;
}


我收到此消息:线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x0)

在这里:if (scanf("%d/%u",&(a->n), &(a->d)) == 1) a->d=1;

c
1个回答
1
投票

您正在创建指向没有什么特别的指针,然后将其传递给永不初始化它们,为它们分配内存并相信它们是有效的函数,但不是这样的函数。” >

请记住,point* a是指针,而不是分配。

一个简单的解决方案是使用局部变量而不是指针:

int main(void)
{
    rationalNumber z;
    point a;

    load_point(&a, input);

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.