Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointers nested

Tags:

pointers

I can't understand code from CCS C compiler. The code is:

addr[0] =  *(((char*)&block_number)+2);

I guess that "&block_number" is address of variable named "block_number". After that I get lost.

like image 802
user1941580 Avatar asked Jul 10 '26 07:07

user1941580


2 Answers

Let's split this up:

*(ptr+2)

is equivalent to:

ptr[2]

Here, ptr is a char* pointing to the address of block_number.

So say block_number is an instance of a struct like this:

struct {
  char a;
  char b;
  char c;
  char d;
} block_number

Then addr[0] will contain the value of c (assuming the values are packed with no space between them). This is because the pointer to block_number is converted to a char*, and then indexed like an array.

So basically, this reads the third byte in block_number.

like image 113
loganfsmyth Avatar answered Jul 13 '26 19:07

loganfsmyth


It is a bit difficult to say when one do not know what block_number is. Let say it is a integer with the value 0xdeadbeef:

unsigned int block_number = 0xdeadbeef;

on a little endian architecture (i.e. x86):

*(char *)&block_number is 0xef, 
*(((char *)&block_number) + 1) is 0xbe and
*(((char *)&block_number) + 2) is 0xad.

While if block_number is a char then *(((char *)&block_number) + 2) could point to a adjacent variable, let say block_number is declared on the stack:

char a = 0xab, b = 0xbc, block_size = 0xcd, c = 0xde, d = 0xef;

Then ((char *)&block_size + 2 could point to i.e. a and *(((char *)&block_size + 2) would return 0xab. Because the stack is most commonly ordered from max address to lower addresses:

heap                                              stack
[... ->     <- d    | c    | block_size | b    | a    ]
[... ->     <- 0xef | 0xde | 0xcd       | 0xbc | 0xab ]

But this is never certain as C does not put any constraints on the compiler where to locate a and the location is probably undefined.

For sizeof(char) it is always 1. char is one character, that is why you do not need to specify length*sizeof(char) to malloc if you want to allocate memory. You only do:

int length = 20;
void *mem = malloc(length);
like image 33
emil Avatar answered Jul 13 '26 21:07

emil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!