c - 同一内存位置上的结构和数组声明

标签 c arrays memory struct

我正在从事一个嵌入式 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.与其使用指针访问结构体的成员,不如使用位于同一内存位置的数组合适吗?

  1. 它会导致内存问题吗?

能否请您帮助我理解 stuct 和 array 在这种特定情况下的用法。

谢谢

库纳尔

最佳答案

开发该代码的(奇怪的)程序员正在“模拟”union能够访问与 struct example_struct 相同的位置或 bytebyte .

喜欢:

#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/

相关文章:

c - GDB [[Inferior 1 (process 2710) exited with code 06]] 奇怪的输出

windows - 设置 Windows 进程(或用户)内存限制

arrays - 在数组 VBA 中查找特定 Object.Name 字符串的快速方法

java - 仅打印工作日

c# - 我是否需要在 .NET 中显式调整堆栈大小?

c++ - 如何在函数中释放内存

c - 从类型 `' 分配给类型 ]'` 时不兼容的类型

c - 为什么这段代码仍然有效?

c - 为什么这会给出垃圾字符?

javascript - 从嵌套结构递归映射 3d.js 图形节点和链接