Hello,

Well, this is not a question directly related to programming, so kindly excuse me for that.
i have a small doubt regarding endianess and dereferencing of elements

This is what i tried:

#include <stdio.h>

int main(void)
{
	int s = 0xFFFFFAFF - 1; 
	int *p = &s;

	unsigned char *ptr = (unsigned char *)&s;

	printf("one %u\n", p);
	printf("two %u\n", ptr);

	printf("%x\n", *ptr);
	printf("%x\n", *(ptr + 1));
	printf("%x\n", *(ptr + 2));
	printf("%x\n", *(ptr + 3));

	return 0;
}

o/p:
one 3219961744
two 3219961744
fe
fa
ff
ff

Now, mine is a little endian machine(Intel).

Now, my question is, how exactly is the dereferencing of the pointer take place? i mean the bytes are placed as fe fa ff ff. But the processor needs to fetch in the reverse order, starting from address + sizeof(int) right?

Why is this method followed?

PS: is %u Ok for printing out addresses? (since they are always positive)

>>PS: is %u Ok for printing out addresses
If you want to see the address in hex instead of decimal use %p

This example will show you how data is stored in memory

#include <iostream>

int main()
{
    int x = 123;
    char buf[sizeof(int)];
    *(int *)buf = x;
    for(int i = 0; i < sizeof(int); i++)
    {
        std::cout << (int)buf[i] << ' ';
    }
    std::cout << '\n';
}
commented: Thanks +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.