繁体   English   中英

c-指向结构内部结构的空指针

[英]c - void pointer to struct inside a struct

编辑:

我得到的确切错误是:错误:在不是结构或联合的内容中请求成员“ q”

我更正了我在代码中留下的错别字。 在将其格式化为SO(驼峰盒..)时发生了。

语境

设置指向结构的空指针的问题。

我的最初目标是 :我想从空指针指向结构。 pointMe.a将指向pointMe2,这样我就可以用整数设置pointMe2.q。

我的最终目标是 :在重用我的pointMe结构的同时,能够将空指针投射到任何对象上。 也许我可以指向一个结构,然后再指向一个char或一个整数。 我认为是多态的。

失败

显然,在下面的代码3)中,q不是结构或联合的一部分。 看着指针的地址,我知道我已经很近了,但是还没有到那儿。

我的时髦代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {

    void * a;

}pointMe;

typedef struct {

    int q;

}pointMe2;

int main(void)
{

    pointMe arrow;
    pointMe2 * flesh;

    flesh = malloc(sizeof(pointMe2));
    flesh->q = 4;

    printf("1)\n Value: %d Address: %p\n",flesh->q,flesh );

    arrow.a = flesh;
    printf("2)\n arrow.a's address: %p flesh's address: %p\n",arrow.a,flesh );

    printf("3)\n arrow.a's address: %p Value of q : %d\n",arrow.a, *(arrow.a)->q );

    free(flesh);
    return 0;
}
printf("3)\n arrow.a's address: %p Value of q : %p\n",arrow.a, *(arrow.a)->q );

.a成员是一个void指针。 取消引用void指针是不可能的,因为不存在void类型。 您必须先将指针强制转换为正确的类型:

printf("3)\n arrow.a's address: %p Value of q : %p\n",
       arrow.a,
       ((pointMe2 *)arrow.a)->q);

另请注意, %p转换说明符期望传递一个void指针。 当打印flesh的值时,需要将其转换为void *然后printf

printf("1)\n Value: %d Address: %p\n", flesh->q, (void *)flesh );

您的代码中有一些错误[我认为是错别字]。

  1. pointme arrow; 应该是pointMe arrow; 等等。 [在下面的代码中修改]
  2. value of应为[ int类型]的值,因此将%dprintf()

检查以下代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {

    void * a;

}pointMe;

typedef struct {

    int q;

}pointMe2;

int main(void)
{

    pointMe arrow;            //corrected
    pointMe2 * flesh;         //corrected

    flesh = malloc(sizeof(pointMe2));
    flesh->q = 4;

    printf("1)\n Value: %d Address: %p\n",flesh->q,flesh );

    arrow.a = flesh;
    printf("2)\n arrow.a's address: %p flesh's address: %p\n",arrow.a,flesh );

    printf("3)\n arrow.a's address: %p Value of q : %d\n",arrow.a, ((pointMe2 *)(arrow.a))->q );  //corrected

    free(flesh);
    return 0;
}

使用*(arrow.a).q(arrow.a)->q

暂无
暂无

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

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