In C, what happens in memory when we throw int into struct *?

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

static char arr[1000];

What happens to arr

when i do

node* first_block = (node*)arr;

?

I understand that this is equal

node* first_block = (node*)&arr[0];

but

sizeof(node) = 8;
sizeof(arr[0])= 1;

so the first element overrides the next seven elements in arr, because now it's struct? Could you please explain this cast to me?

+4
source share
4 answers

When you write

node* first_block = (node*)arr;

you do not change anything in memory, you get a pointer to a region in memory, the type of pointer determines how the region is processed with respect to pointer arithmetic.

first_block->next will be a pointer, which is determined by the characters in the array.

as a comparison they say that you have a char * pointer for the same array

(if arr is declared in the global scope, it will contain 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

* q, , q , * p node char arr, node.

+5

, type *pointer,

type *next = pointer + 1;

type *next = &pointer[1];

type *next = ((char *)pointer + sizeof(type));
0

, "".

- / .

/ ( ) - , .

0

, . C , .

You can treat a sequence of 8 bytes as 8 ASCII ( char[8]) or characters struct node. Casting simply changes the presentation of the data, but the data is not affected.

0
source

All Articles