[英]In C, what happens in memory when we do cast int to struct*?
typedef struct block
{
size_t size;
struct block* next;
} node;
static char arr[1000];
What happens with arr arr会发生什么
when I do 当我做
node* first_block = (node*)arr;
? ?
I understand that this is equal to 我明白这等于
node* first_block = (node*)&arr[0];
but 但
sizeof(node) = 8;
sizeof(arr[0])= 1;
so first element override next seven elements in the arr, because it's struct now ? 所以第一个元素覆盖arr中的下七个元素,因为它现在是struct? Can you explain me this cast, please ?
你能解释一下这个演员吗?
When you write 当你写作
node* first_block = (node*)arr;
you are not changing anything in memory, you get a pointer to the area in memory, the type of the pointer determines how the area is treated in regard to pointer arithmetic. 你没有改变内存中的任何东西,你得到一个指向内存区域的指针,指针的类型决定了如何处理关于指针算术的区域。
first_block->next
will be a pointer that is determined by the characters in the array. first_block->next
将是一个由数组中的字符确定的指针。
as a comparison say you have a char* pointer to the same array 比较说你有一个指向同一个数组的char *指针
(if arr is declared at global scope it will contain 0's) (如果arr在全局范围内声明,它将包含0)
char* q = arr;
node* p = (node*)arr;
arr[1000]
+----------------------+
q -> | | | | |
| 0 | 0 | ... | 0 |
p -> | | | | |
+----------------------+
when you do 当你这样做
q = q + 1;
// you move the character pointer one char forward since q is a char pointer
when you do 当你这样做
p = p + 1;
// you move the node pointer sizeof(node) chars forward since p is a node pointer
when you do *q you get the character value of where q points to, *p gives you the node value from the char arr, ie the characters are interpreted as a node struct. 当你执行* q时,你得到q指向的字符值,* p给你char arr的节点值,即字符被解释为节点结构。
It's related to pointer arithmetic, when you have a pointer type *pointer
, and you do this 它与指针算法有关,当你有一个指针
type *pointer
,并且你这样做
type *next = pointer + 1;
or 要么
type *next = &pointer[1];
you are effectilvely doing this 你是有效地做到这一点
type *next = ((char *)pointer + sizeof(type));
nothing happens to the data when the code does a 'cast'. 当代码执行'强制转换'时,数据没有任何反应。 However,
然而,
the compiler will treat that data differently for the duration/scope of the cast. 编译器会根据强制转换的持续时间/范围对数据进行不同的处理。
the duration/scope of the cast is (almost always) only the statement that contains the cast. 演员的持续时间/范围(几乎总是)只包含演员表的声明。
Memory does not know about types, so nothing happens to it when casting. 内存不知道类型,所以在投射时没有任何反应。 Types in C just describe how the bytes in memory are interpreted.
C中的类型只描述了如何解释内存中的字节。
You can treat a sequence of 8 bytes as 8 ASCII characters ( char[8]
) or a struct node
. 您可以将8个字节的序列视为8个ASCII字符(
char[8]
)或struct node
。 Casting just changes the view of the data, but the data is not affected. 转换只是更改数据视图,但数据不受影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.