注册 登录
编程论坛 C语言论坛

结构体指针访问结构体成员

数据总线 发布于 2021-10-11 09:09, 1489 次点击
#include<stdio.h>
#include<stdlib.h>
#include<string.h>


typedef struct
{
    char a;
    int b;
    float c;
}struct_A_s;

typedef struct
{
    char a;
    int b;
    struct_A_s obj;
    float c;
}struct_B_s;


struct_B_s sObj =
{
    10,
    1000,
    .obj.a = 10,
    .obj.b = 1000,
    .obj.c = 0.1,
    9.99
};

int    main()
{
   struct_B_s *p = &sObj;

    printf("a=%d\n",p->a);
    printf("a=%d\n",p->b);
    printf("obj-a=%d\n",p->obj->a);//可不可这样子访问
    printf("obj-b=%d\n",p->obj->b);//可不可这样子访问
    printf("obj-c=%.2lf\n",p->obj->c);//可不可这样子访问
    return 0;
}
1 回复
#2
自由而无用2021-10-11 09:31
//online parser: https://www.bccn.net/run/
程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
    char a;
    int b;
    float c;
}struct_A_s;

typedef struct
{
    char a;
    int b;
    struct_A_s obj;
    float c;
}struct_B_s;


struct_B_s sObj =
{
    10,
    1000,
    .obj.a = 10,
    .obj.b = 1000,
    .obj.c = 0.1,
    9.99
};

int main(int argc, char *argv[])
{
    struct_B_s *p = &sObj;

    printf("a = %d\n", p->a);
    printf("a = %d\n", p->b);
    printf("obj-a[mem] = %d, obj-a[ptr] = %d\n", p->obj.a, (&p->obj)->a);
    printf("obj-b[mem] = %d, obj-b[ptr] = %d\n", p->obj.b, (&p->obj)->b);
    printf("obj-c[mem] = %.2lf, obj-c[ptr] = %.2lf\n", p->obj.c, (&p->obj)->c);

    return 0;
}


output sample:
a = 10
a = 1000
obj-a[mem] = 10, obj-a[ptr] = 10
obj-b[mem] = 1000, obj-b[ptr] = 1000
obj-c[mem] = 0.10, obj-c[ptr] = 0.10
#3
apull2021-10-12 23:40
printf("obj-a=%d\n",p->obj->a);//可不可这样子访问
printf("obj-b=%d\n",p->obj->b);//可不可这样子访问
printf("obj-c=%.2lf\n",p->obj->c);//可不可这样子访问

上面3中不能访问。
p是指针,所以用->,而p->obj里的obj不是指针,所以不能用->进行访问,要用.访问。
改成下面方式即可。
printf("obj-a=%d\n",p->obj.a);
printf("obj-b=%d\n",p->obj.b);
printf("obj-c=%.2lf\n",p->obj.c);
1