【发布时间】:2020-12-29 18:02:26
【问题描述】:
我想了解如何将 char 数组转换为 struct 类型。我做了以下事情:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int a;
int b;
int c;
} test;
int main()
{
char data[20];
strcpy(data, "text");
test *ptr = (test*)data;
return 0;
}
为了尝试了解正在发生的事情,我添加了以下几行:
如果我添加行“printf(“%s”, ptr)”,尽管有警告,程序输出是“文本”。
接下来,如果在该行之前我初始化了一个字段,比如 ptr->a = 1,那么前一个 printf 的输出将是一些奇怪的字符。
我猜在转换之后,-data-指针指向的内存被扩展为保存结构字段。我的问题是在转换后尝试访问数据。
那么,我的第一个问题是,当上述转换发生时,内存中发生了什么?
另外,我怎样才能从 -ptr- 指针中取回原始数据?
【问题讨论】:
-
Nothing whatsoever is happening in this program。没有可观察到的行为,一个好的编译器会将其全部转换为无操作。修改后,坏事可能会发生,也可能不会发生。如果您想讨论修改后的程序,请发布修改后的程序,而不是要应用的修改列表。
-
C 标准规定:
A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer.
标签: c