我的数据结构如下:
typedef struct struct2 {
uint8_t num;
uint8_t action;
uint8_t id;
} struct2_t;
typedef struct struct1 {
uint8_t title;
struct2_t* content;
} struct1_t;
我给一个结构指针分配了一个内存空间并打印出值。
void main(){
const uint8_t msg[5] = {
5, 4, 3, 2, 1
};
struct1_t *req = NULL;
req = (struct1_t *)msg;
printf("%d ", req->title);
printf("%d ", req->content->num);
printf("%d ", req->content->action);
printf("%d ", req->content->id);
}
结果是:
五五四三
我以为是5 4 3 2?
另外,在另一个地方,我复制缓冲区中的内容并执行类似的操作。
void main(){
const uint8_t msg[5] = {
5, 4, 3, 2, 1
};
uint8_t *test = NULL;
test = (uint8_t*)malloc(5 + 1);
memset((test), 0x00, 5);
memcpy(test, msg , 5);
struct1_t *req = NULL;
req = (struct1_t *)test;
printf("%d ", req->title);
printf("%d ", req->content->num);
printf("%d ", req->content->action);
printf("%d \n", req->content->id);
}
但这次我不能访问struct2指针
五
分段故障(堆芯转储)
有人能告诉我我缺了什么吗谢谢你的帮助
最佳答案
您似乎缺少的是对何时将dot
(.
)运算符与结构一起使用以及何时使用arrow
(->
)运算符的清晰理解。
规则很简单。如果有struct
,则可以使用.
运算符访问其成员。如果有pointer to a struct
,则可以使用->
箭头运算符访问其成员。当您有包含struct
的pointer to a struct
时,请使用其中一个。
下面的示例应该清楚说明这一点,并提供使用content
指针指向具有自动存储s2
的结构和存储在动态分配内存“s3”中的结构的示例。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
enum { MAXL = 128, MAXC = 512 };
typedef struct struct2 {
uint8_t num;
uint8_t action;
uint8_t id;
} struct2_t;
typedef struct struct1 {
uint8_t title;
struct2_t *content;
} struct1_t;
int main (void) {
struct2_t s2 = { 5, 4, 3 }, *s3 = NULL;
struct1_t s1 = { 2, &s2 }; /* content initialized to s2 */
/* using address of s2 as content */
printf ("\n title : %" PRIu8 "\n"
" num : %" PRIu8 "\n"
" action : %" PRIu8 "\n"
" id : %" PRIu8 "\n", s1.title,
s1.content->num, s1.content->action,
s1.content->id);
/* dynamic allocation of s3 */
if (!(s3 = calloc (1, sizeof *s3))) {
fprintf (stderr, "error: virtual memory exhausted.\n");
return 0;
}
s3->num = 8; /* assignment of values to s3 */
s3->action = 7;
s3->id = 6;
s1.content = s3; /* update content pointer to s3 */
/* using address of s3 as content */
printf ("\n title : %" PRIu8 "\n"
" num : %" PRIu8 "\n"
" action : %" PRIu8 "\n"
" id : %" PRIu8 "\n", s1.title,
s1.content->num, s1.content->action,
s1.content->id);
free (s3); /* don't forget to free all memory you allocate */
return 0;
}
示例输出
$ ./bin/structnested
title : 2
num : 5
action : 4
id : 3
title : 2
num : 8
action : 7
id : 6
看看这个例子,让我知道如果你有任何进一步的问题,或者如果我错过了你的问题的一部分,让我也知道。
关于c - 类型转换为其中具有另一个结构ptr的结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37752859/