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

asi*_*sir 0 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);
}
Run Code Online (Sandbox Code Playgroud)

我得到o/p但是有一个警告

 warning: assignment makes pointer from integer without a cast
Run Code Online (Sandbox Code Playgroud)

 warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘int *’
Run Code Online (Sandbox Code Playgroud)

如何在struct test中输入值到*y

Dou*_* T. 6

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

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

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

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

free(a->y);
free(a);
Run Code Online (Sandbox Code Playgroud)