向结构成员输入数据是一个指针

时间:2011-02-28 12:29:39

标签: c

#include<stdio.h>
#include<stdlib.h>
struct test
{
    int x;
    int *y;
};

main()
{
    struct test *a;
    a = malloc(sizeof(struct test));

    a->x =10;
    a->y = 12;
    printf("%d %d", a->x,a->y);
}

我得到o / p但是有警告

 warning: assignment makes pointer from integer without a cast

 warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘int *’

如何在struct test

中向* y输入值

1 个答案:

答案 0 :(得分:6)

要访问,您需要取消引用由表达式a-&gt; y返回的指针来操纵指向的值。为此,请使用一元*运算符:

您还需要为y分配内存以确保它指向某个内容:

a->y = malloc(sizeof(int));
...
*(a->y) = 12;
...
printf("%d %d", a->x,*(a->y));

并确保以与malloc'd相反的顺序释放malloc数据

free(a->y);
free(a);