Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning values to a pointer

I have a bit of trouble understanding the concept of pointers, and one of them is this:
Let us declare an integer type variable n, and a pointer to it *p.
int n=23,*p;
Now,
p=&n;, if I am not wrong, assigns the address of variable n (say, 3000) to p.
So cout<<p<<" "<<*p; would output 3000 and 23 respectively.
My doubt here is that suppose we did something like this:
p=5; i.e. assigning a numerical value to a variable designed to hold memory locations, what would happen?
Is the variable moved to the memory location '5' (most likely not) or is the pointer just converted to an 'int' and made to hold the value 5? I would have tried this out myself, only messing with my system's memory made me have second thoughts.

Also, when we declare any variable (suppose int with 2 bytes space), is it stored in a random memory location like 3000, 101, 2700 or something, or is it stored in 0,2,4,etc.? And is the next variable declared stored right in the next one (like 3002, 103 or 2702), or is there some kind of gap in-between?

like image 326
Anchith Acharya Avatar asked Feb 05 '23 05:02

Anchith Acharya


1 Answers

In your example this is a compiler error.

However what I assume you wanted to do was this:

int n =23, *p;
p = &n;
//Change the value of p to 3000, p now points to address 3000
p = reinterpret_cast<int*>(3000); 
//Check if the address of n has changed
std::cout << "Address of n : " << reinterpret_cast<int>(&n) << std::endl; 

As you can tell when you run this code. The address of n does not change.

For your second question.

Yes and No :)

If you define two variables next to each other they may be next to each other in memory.

 int a,b,c,d;
 char c = 1;
 short s = 1;
 void* p = nullptr;
 int i = 1;

 std::cout << "a is at: " << reinterpret_cast<int>(&a) << std::endl;
 std::cout << "b is at: " << reinterpret_cast<int>(&b) << std::endl;
 std::cout << "c is at: " << reinterpret_cast<int>(&c) << std::endl;
 std::cout << "d is at: " << reinterpret_cast<int>(&d) << std::endl;
 std::cout << "Char is at: " << reinterpret_cast<int>(&c) << std::endl;
 std::cout << "Short is at: " << reinterpret_cast<int>(&s) << std::endl;
 std::cout << "Pointer is at: " << reinterpret_cast<int>(p) << std::endl;
 std::cout << "Int is at: " << reinterpret_cast<int>(&i) << std::endl;

This behavior is caused the compiler determining where to stick everthting. It may or may not exist next to each other. If you want to guarantee they exist next to one another, use an array.

int arr[] = {1,2,3,4,5,6,7};
int * p = &arr[0]; //get address of first element
for(int i = 0 ; i < 7; ++i)
    std::cout << "Value at address: " << reinterpret_cast<int>(p+i) 
        << " is: " << *( p + i) << std::endl;
like image 188
user3853544 Avatar answered Feb 07 '23 18:02

user3853544