在C中,当我们将int转换为struct*时,内存会发生什么?

4 c

typedef struct block
{
   size_t size;
   struct block* next;
} node;

static char arr[1000];
Run Code Online (Sandbox Code Playgroud)

arr会发生什么

当我做

node* first_block = (node*)arr;
Run Code Online (Sandbox Code Playgroud)

我明白这等于

node* first_block = (node*)&arr[0];
Run Code Online (Sandbox Code Playgroud)

sizeof(node) = 8;
sizeof(arr[0])= 1;
Run Code Online (Sandbox Code Playgroud)

所以第一个元素覆盖arr中的下七个元素,因为它现在是struct?你能解释一下这个演员吗?

And*_*rsK 6

当你写作

node* first_block = (node*)arr;
Run Code Online (Sandbox Code Playgroud)

你没有改变内存中的任何东西,你得到一个指向内存区域的指针,指针的类型决定了如何处理关于指针算术的区域.

first_block->next 将是由数组中的字符确定的指针.

比较说你有一个指向同一个数组的char*指针

(如果arr在全局范围内声明,它将包含0)

char* q = arr;
node* p = (node*)arr;


                arr[1000]
          +----------------------+
  q  ->   |   |   |          |   |
          | 0 | 0 | ...      | 0 |
  p ->    |   |   |          |   |
          +----------------------+
Run Code Online (Sandbox Code Playgroud)

当你这样做

q = q + 1;  

// you move the character pointer one char forward since q is a char pointer
Run Code Online (Sandbox Code Playgroud)

当你这样做

p = p + 1;  

// you move the node pointer sizeof(node) chars forward since p is a node pointer
Run Code Online (Sandbox Code Playgroud)

当你执行*q时,你得到q指向的字符值,*p给你char arr的节点值,即字符被解释为节点结构.