Assume that an integer variable declared, X = 1;. and address of X is start from 2001 until 2004. So, my question is, can i only read the value that the address 2002 has?
i'm not sure that my question clearly brings out my problem...so please reply me :D thanks!
1 2 3 4 5 6
//code shown below is what i tried on my compiler, and i failed to run it.
int x = 1; // assume address x is 2001
void *p = (int *) 2002; // pointer p is pointing at 2002, void *p/ int *p? not sure..
cout << *p; //print out the value
I think my question is ambiguous. let me try to explain my problem another way.
an Integer value has 4 byte, assume that byte1, byte2, byte3, byte4.
and int x = 1025;
byte1 = 00000000
byte2 = 00000000
byte3 = 00000010
byte4 = 00000001
0000 0000 0000 0001
Can i only read the value in byte3, which has the value of 00000010?
#include <iostream>
int main ()
{
int x = 1025 ;
constint* p = &x ;
// a valid value of a non-null object pointer type represents the address of a byte in memory.
// for narrow character types, all bits of the object representation participate in the value representation
// for unsigned narrow character types, each possible bit pattern of the value representation
// represents a distinct number.
using byte = unsignedchar ;
const byte* pbyte = reinterpret_cast<const byte*>(p) ;
// print out the integer values of the bytes. note: integral promotion with unary +
// also see: endianness https://en.wikipedia.org/wiki/Endiannessfor( std::size_t i = 0 ; i < sizeof(x) ; ++i ) std::cout << +pbyte[i] << ' ' ;
std::cout << '\n' ;
}
> Not really clear about the datatype byte, and the using keyword.
using byte = unsigned char ; is a type alias declaration;
it states that the name byte is a synonym for unsigned char
using byte = unsigned char ; is equivalent to typedef unsigned char byte ;
With a legacy (pre C++11) C++ compiler, use typedef unsigned char byte ;
The same code, without the type alias, would be:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
int main ()
{
int x = 1025 ;
constint* p = &x ;
constunsignedchar* pbyte = reinterpret_cast<constunsignedchar*>(p) ;
for( std::size_t i = 0 ; i < sizeof(x) ; ++i ) std::cout << +pbyte[i] << ' ' ;
std::cout << '\n' ;
}
A type alias declaration introduces a name which can be used as a synonym for the type denoted by type-id. It does not introduce a new type and it cannot change the meaning of an existing type name. There is no difference between a type alias declaration and typedef declaration. http://en.cppreference.com/w/cpp/language/type_alias