简体   繁体   English

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

[英]to input data to structure member is a pointer

#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);
}

I get the o/p but there is a warning 我得到了o / p,但有警告

 warning: assignment makes pointer from integer without a cast

and

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

how to input a value to *y in struct test 如何在结构测试中向* y输入值

To access, you need to dereference the pointer returned by the expression a->y to maniputlate the pointed at value. 要进行访问,您需要取消引用表达式a-> y返回的指针,以运算所指向的值。 To do this, use the unary * operator: 为此,请使用一元*运算符:

You also need to allocate memory for y to make sure it points at something: 您还需要为y分配内存,以确保它指向某个对象:

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

And be sure to free malloc'd data in the reverse order it was malloc'd 并且确保以与malloc'd相反的顺序释放malloc'd数据

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM