我正在从事一个嵌入式 C 项目。我无法理解数组和结构在代码中的使用。
例如:
结构:
struct example_struct{
char a;
char b;
char array[4];
}
注意:Int 和 char 的默认大小是 1 个字节。
我使用的编译器提供了使用'@'符号为变量和其他参数分配内存的功能
例如:
内存分配
int example @ 0x125
// Compiler allocate the RAM memory location 0x125 to my variable "example"
问题:
编写这个项目的人使用了下面给出的结构和数组
example.h
struct example_struct{
char a;
char b;
char array[4];
}
内存.h
volatile struct example_struct node @ 0x130 ;
//allocate memory location 0x130 - 0x135 to node
volatile char buffer[6] @ 0x130;
//allocate memory location 0x130 - 0x135 to buffer
问题
1.与其使用指针访问结构体的成员,不如使用位于同一内存位置的数组合适吗?
- 它会导致内存问题吗?
能否请您帮助我理解 stuct 和 array 在这种特定情况下的用法。
谢谢
库纳尔
最佳答案
开发该代码的(奇怪的)程序员正在“模拟”union
能够访问与 struct example_struct
相同的位置或 byte
每byte
.
喜欢:
#pragma pack(1)
union struct_and_raw_byte_access
{
struct example_struct
{
char a;
char b;
char array[4];
}structured;
char buffer[sizeof(struct example_struct)];
};
#pragma pack()
int main(void)
{
union struct_ad_raw_byte_access temp;
int i;
temp.structured.a = 1;
temp.structured.b = 2;
temp.structured.array[0] = 3;
temp.structured.array[1] = 4;
temp.structured.array[2] = 5;
temp.structured.array[3] = 6;
for (i=0; i< sizeof(temp.buffer)/sizeof(temp.buffer[0]); i++)
printf("buffer[%d] = %d\n", i, temp.buffer[i]);
return 0;
}
关于c - 同一内存位置上的结构和数组声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35556742/