通过C中的void函数初始化指向结构的指针

时间:2016-06-15 17:00:55

标签: c function pointers struct

让我的结构成为:

typedef struct{
    double x;
    double y;
   } punt;

typedef struct{
    char tip;
    punt infEsq
    punt supDret;
   } rectangle;

typedef struct{
    rectangle *llista;
    int numRect;
    int midaMax;
   } taulaRectangle;

语境化,

"平底船"代表一点。

"矩形",char表示它是方形[q]还是矩形[r],这两个点是左下点(infEsq)和右上角(supDret)矩形。

" TaulaRectangle"映射结构类型"矩形"的列表(或表),指示它有多少个矩形[numRect],以及它可以容纳多少[midaMax](如果我没有错,则指示[的尺寸] llista])。

现在我想编写一个函数来初始化指向" taulaRectangle"像这样:

void initaula(taulaRectangle *t,int n) /*n is associated to midaMax*/

我不会在编写有效的初始化函数时发表我的意图,因为我相信它们并不接近我想要达到的目标,尽管这是类似的场景,我尝试过类似的东西:

    void inipunt(punt *b){
    b->x=0;
    b->y=1;
    return;
    }
    int main (void){
    double b,n;
    punt *a;
    inipunt(a);
    puts("guay");
    a.x=b;
    a.y=n;
    printf("a.x=%lf a.y=%lf",b,n); /*I know this association is not necessary
                                     but if I directly print a.x a.y it does
                                     not work either, also a fail is *(a.x),*
                                     (a.y) */
    return 0;
    }

编译器(gcc -ansi -Wall)返回:

  

final1.c:30:2:错误:请求成员'x'的东西不是a   结构或联合a.x = b; ^ final1.c:31:2:错误:请求   成员'y'的东西不是结构或联合a.y = n; ^

合成,我希望能够声明指向" taulaRectangle"并使用" void initaula()"初始化它,我输入上面的例子,因为我相信我想要在两个函数中实现的是类似的,除了在" void inipunt()"我没有为结构中的指针分配内存,我认为问题在于我如何处理我的void函数中的结构指针。

很抱歉这个长期的问题,如果有人可以提供帮助,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

正如Eugene在评论中指出的那样,指针没有被分配。

当你执行punt *a;时,你只是分配一个指向结构的指针,但它还没有指向任何东西。它没有初始化。
保持未初始化的变量,因为它们可以有任何价值。你不知道未初始化的指针指向什么。

您有两个解决此问题的方法:

  • 通过执行punt a;为堆栈中的结构分配空间。在这种情况下,a是结构。
  • 通过执行punt *a = malloc(sizeof(punt))为堆中的结构分配空间。在这种情况下,a是指向结构的指针。

如果你在堆栈中分配空间,要获得a的指针,你应该&a 请记住,要访问指针后面的结构,请使用->代替.

这应该有效:

void inipunt(punt *p) {
    p->x = 0;
    p->y = 1;
}
int main() {
    punt a;
    inipunt(&a);
    printf("%lf %lf\n", a.x, a.y);
    punt *b = malloc(sizeof(punt));  // You should check if it returns NULL, in case of an error.
    inipunt(b);
    printf("%lf %lf\n", b->x, b->y);
    return 0;
}