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
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
To access, you need to dereference the pointer returned by the expression a->y to maniputlate the pointed at value. To do this, use the unary * operator:
You also need to allocate memory for y to make sure it points at something:
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
free(a->y);
free(a);
精彩评论