Can i somehow access a value if i know its address? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
say we have a variable
int var = 3000;
int *pt;
pt=2293572; //where &var=2293572
Question is basically indirectly accessing values stored at memory locations, by just knowing the memory address?
If not in c,cpp can we use some other language for it?

It sounds like you are asking how to cast an integer to a pointer and assign a value to a memory location using it.
int var = 3000;
int *pt;
pt= (int*) 2293572;
// Assignment
*pt = 2; // now var = 2
Note that when you do this, you should observe the usual caveats, as Matt McNabb mentioned below.
whether the cast works is implementation-defined
the address might not be correctly aligned for int
you'd better make sure you have the right address

While running this program you might have got the address 2293572 for "var", but its not necessary that you will get the same address every time you run your program.
Therefore its not a good practice to, explicitly assign an address to a variable and then try to access the value at that address.
You need to use pointers if you want to play around with addresses in c
Try this :
#include<stdio.h>
int main()
{
int var = 100; // initialise a variable
int *ptr; // declare a pointer variable; a pointer is used to store the address
// (logical address, to be specific ) of a variable.
ptr = &var; // assign the address of the variable to the pointer
printf("\nvar = %d", *ptr); // access the value stored at that address. This is also
// dereferencing.
}

The correct way for the example given in your question:
int var = 3000;
int *pt = &var;
int x = *pt; // read-access (same as 'int x = var')
*pt = 12345; // write-access (same as 'var = 12345')
If you have a "pure" address (without the name of the variable allocated at that address):
int *pt = (int*)2293572;
int x = *pt; // read-access
*pt = 12345; // write-access
If the underlying HW architecture or the designated compiler at hand do not support unaligned load/store operations, then you have to ensure that the address is divisible by the size of the data-type.
For example, in the above code you would have to assert that 2293572 % sizeof(int) == 0.

Int car = 3000; //variable car
Int final;
Int* ptr; // unassigned pointer
Ptr= &car; // variable ptr holds memory location of car.
final = *ptr // this is the dereference
Final will return the integer value 3000.
To be quick and simple, pointers point to memory locations. When you "dereference" you say..."Hey I don't want to know where the number is, I want to know what value is stored there.
The tricky part of c is that it uses dynamic memory allocation, so it will not maintain the same location every time.

Related

Pointer initialization with new keyword and without it [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
When I try to declare in another way a pointer I try to use the new keyword and give it a try:
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
int main ()
{
int *p = new int;
*p = 5;
cout << *p << endl;
return 0;
}
but when I try to declare the same pointer but without the new keyword it gives me an error like the code below:
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
int main ()
{
int *p;
*p = 5;
cout << *p << endl;
return 0;
}
So what is the reason for that error and what is the difference between the two ways?
You should know the differences.
int *p;
Here, p is just a variable on the stack. It hasn't been initialized so it does not point to a specific location on the memory. Thus when you dereference it and assign a value to the underlying location you are invoking some undefined behavior. In other words, you haven't yet allocated any space on the heap to store an int. So here:
*p = 5;
you are probably assigning the value 5 to a location that does not belong to your program.
Now here:
int *p = new int;
*p = 5;
this is fine. The new operator will reserve 4 bytes on the heap memory and return its address and that address gets stored in the p and now p contains an actual and legal address of a block of memory capable of storing an int. So it is safe to dereference p and assign a value to the underlying location.
Important note: You should almost never deal with new/delete or new[]/delete[] operators and raw pointers. Instead, you should use smart pointers and stick to RAII as much as possible.
Therefore, the correct way of doing the above would be like this:
#include<iostream>
#include<memory>
using std::cin;
using std::cout;
using std::endl;
int main ()
{
std::unique_ptr<int> p { std::make_unique<int>( 5 ) };
cout << *p << endl;
return 0;
}
However, using any type of pointers is wasteful in this case since you can also store small types on the stack:
int num { 5 };
This is the preferred way of storing values unless you are desperate to use dynamic memory allocations (for some reason, like maybe you want an object to have dynamic storage duration, or maybe the object is large and won't fit on the stack).
new int occupies a new memory space on the heap, and p points to that memory space. But on the second example, you didn't specify where p points to (so p can point to anywhere, but you try to assign the memory address p points, so it cause undefined behaviour.

how can i hold pointer object in array? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm a newbie. since my code is so long I can't edit it for being reproducible so I will show you what I did in a simple way
I have a Team class. I want to hold all my objects in an array so that I can reach them somewhere else and map for some data.
so I did a function basically doing this (exactly this part b[1] = a;)
int* a; // represent my object
int *b = new int[2]; //represent my static object pointer
b[1] = a;
error saying cant assign int = *int
yes absolutely true but I have to hold my object in the array. and I thought this could work but no... is there a way to hold an object in an array or can I say give me space for *int, during pointer initializing?
A better way would be to use std::vector to hold your class objects. The advantage of using a std::vector is that then you won't have to deal with memory management explicitly. vector will take care of it.
In addition, i will also recommend using smart pointers.
To solve your error above you can use the following example:
int i = 0, j = 0;//int objects
int* p = &i, *q = &j; //pointer to int objects
int **b = new int*[2]; //note i have added * on both the left and right hand side.
b[0] = p;
b[1] = q;
//dont forget to use delete below
Note you should use std::vector and smart pointers, but i have added an example so that you can see how to remove the error and use this example as a reference.

What is the difference betwene int *p and int * p = new int; [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have 3 questions:
Q1. When we create the object using the new operator, following is the syntax:
pointer_variable = new data-type //To create an object
pointer_variable = new data-type(value); //To create an object with value
pointer_variable = new data-type[size]; //To create an array
Why always there is a pointer_variable on L.H.S?
Q2. What is the difference between declaring and assigning pointers with and without the new operator?
Consider the following code snippet and output to understand the question:
int a = 10, b=20;
int *p;
p = &a;
int *q = new int;
q = &b;
cout<<"P is: "<<p<<" : "<<*p<<endl<<"Q is: "<<q<<" : "<<*q<<endl;
Output of the above code:
P is: 0x61ff04 : 10
Q is: 0x61ff00 : 20
Q3. When we say, with a new operator we can dynamically allocate memory to the array at run time when we don't know the size of the array at compile time. We can do this without new operator as given below:
cout<<"Enter the size of an array"<<endl;
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=0;i<n;i++)
{
cout<<arr[i];
}
Then what is exactly the need to use the new operator for arrays?
Why always there is a pointer_variable on L.H.S?
Because new-expression results in a pointer.
What is the difference between declaring and assigning pointers with and without the new operator?
new-expression (not operator new) constructs a new object (and, optionally, allocates memory for it).
We can do this without new operator as given below
In fact, we cannot, according to the C++ Standard. Some compilers just allow this construct as a non-standard language extension.
Every good C++ book for beginners will explain these in more details.
in C++, a typical new expression allocates memory on the heap, and returns a pointer to that memory.
Re Q1: you can save the resulting pointer to a local variable for immediate use: pointer_variable = new int. But you don't have to do that: you could instead use it as an argument to a function: use_pointer(new int).
Re Q2: your code allocates an int on the heap, stores its pointer in local variable q, and immediately overwrites it with the address of local variable b. So what you have done here is write a small memory leak.
Re Q3: variable-sized array is a nonstandard extension to C++, so it will not necessarily work in another compiler. However, when it does work it is just another automatic variable: it will be automatically de-allocated for re-use when you leave the local scope. This is different from new allocations, which last until they are explicitly delete-ed.

Assigning value to the address pointed to by pointer? C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So if an asterisk precedes the pointer name, it refers to the value of the address being pointed to
int anInteger = 30;
int* pointer = &anInteger;
*pointer;
While without having this operator preceding the pointer name, it refers to the value of the pointer itself, i.e. the address of what the pointer is pointing to
pointer;
(PLEASE correct me if I am wrong or if you just got some tips to share :) )
To me, this means that the above code can be translated to following with the assumption that the address of "myInteger" is 1234:
int* pointer = 1234;
30;
1234;
Now to what confuses me - Since that variables refer to locations in memory and names refer to the variables, it is odd to me that you do this when you want to change the value of a variable indirectly using a pointer:
*pointer = 15;
Because that could then be translated to 30 = 15, which does not look very valid..
Also, when you change the value of the variable directly, you do it like this:
anInteger = 33;
where "anInteger" would refer to the variable and thereby the memory address and because of that, I would translate this code to this:
1234 = 33;
SO, because of this, why don't you do this when assigning a new value to a variable indirectly using a pointer:
pointer = 33;
The exact question:
Why do you write *pointername = 33; instead of pointername = 33?
The exact question: Why do you write *pointername = newValue; instead of pointername = newValue?
These are two quite different things. (And you can do both.)
int i = 42;
int x = 23;
int * p = &i;
Now, I can change the content of the location I am pointing to...
*p = 123; // this changes the value of i
Or I can change the location I am pointing to.
p = &x; // now p points to x instead
The "natural" value of a pointer variable is a memory address. So, if I assign to the "naked" p, I am assigning a memory address (which I can obtain, for example, by using the & operator on a variable).
Using the operator *, I dereference the pointer variable. So, if I assign to the "combined" *p, I assign a value of the type pointed to (which ends up at the memory address contained in p).
How about this.
// i is the name of a memory location that now contains 5
int i = 5;
// p is the name of a memory location that contains the address of
// the memory location called i
int* p = &i;
// The memory location pointed to by p (which is also called i) now
// has the value 12 assigned to it
*p = 12;
Let's start with:
anInteger = 27;
rather than translating that to
1234 = 27
Let us write this as
[1234] := 27
which should be read as "the memory cell at address 1234 is assigned the value 27".
Now let us consider
pointer = &newValue;
Obviously (or perhaps not), we will translate that to
[1238] := 1242
which is read as "the memory cell at address 1238 is assigned the value 1242". (Where 1242 is the address of newValue)
Now we need a new way to write the statement where we don't want to alter the value in the pointer variable itself, instead we want to alter the variable that pointer is pointing to. We do that by prefixing with *:
*pointer = 17
Which gets translated into something like:
[[1246]] := 17
which we can read as "the memory cell whose address is given by the contents of memory cell 1246 is assigned the value 17".
The really hard thing to keep straight, is the difference between the value of the pointer, and the thing it is pointing at.
Every spot of memory has two fields, the address field as well as the data field.
For example, you may be at address 0x1234, but that address has a value as well
Address Value
0x1234 |||||| 0x1E
A variable knows about the address as well as the value. when you say
int var = 5;
Var has an address as well as a data field and the assignment operator says to replace the data field with 5.
Address Value
0x1234 |||||| 0x05
A *Pointer * on the other hand has a value of an address. when you write code like
int * varPtr = &var;
You are saying the Value of the varPtr variable is an address.
Address Value
0x1357 |||||| 0x1234
When you "de-point" a pointer like *varPtr, you are going to the address of the value in the pointer and talking about it's value.
*varPtr would be 0x05
varPtr would be 0x1234
var is also 0x05

Segfault Pointers [duplicate]

This question already has an answer here:
C++ Struct Pointer Segfault
(1 answer)
Closed 9 years ago.
I'm new to C++ and pointers and wrote a simple cpp below. I keep on getting a seg fault, but I'm not sure why.
int main() {
int *x = 0;
*x = 8;
return 0;
}
Your integer pointer is null. See this line:
int *x =0
On that line you're setting the memory address of your integer pointer to zero (i.e. nullptr). What I expect you wanted to do is set the value to zero, in which case you'd need to do this:
int main() {
int *x = new int(0);
*x = 8;
return 0;
}
You've declared a pointer to an integer and set it to 0. You haven't actually allocated an integer anywhere. When you assign 8 to the dereferenced pointer, you're trying to write to the memory at location 0. All modern operating systems read and write product the memory at address 0 and anywhere near it to prevent this kind of 'null pointer error'.
Think of memory on a computer as a sheet of graph paper. Each square on the paper has an address, which is the number of squares that came before it. Pointers are for storing these addresses. An int is an actual value, like '5 apples' or '12 downvoting asshats'. These are the values that are stored by writing a number inside one of the rectangles.
However, the OS that manages the system knows that one of the most common kinds of errors people make is forgetting to set up a pointer properly and attempting to write numbers at the very start of the graph paper, so it's designed the graph paper to give you an electric shock if you try to write a number in any of the first few boxes. This is your segmentation fault.
To fix the issue you can either declare an integer on the stack
int i;
int * x = &i;
Declaring something on the stack means the memory will automatically be freed when it leaves scope, i.e. the end of the function.
On the other hand you can allocate a pointer on the heap
int * x = new int;
this means that you're personally responsible for making sure that you free the memory at some later point.
delete x;
Otherwise you're creating a memory leak.
When you define int *x = 0, what you're telling the compiler is "create a integer pointer, x, and set where it points to to 0 (NULL)". What you need to do instead is dynamically create a new pointer. This can be achieved by doing int *x = new int; Then you can change its value. After using it, you should delete it using delete x; to free up its memory.
int *x = 0;
You made an int pointer called x which points to the memory at location 0.
*x = 8;
You tried to write the value 8 into the memory at location 0, which was stored in x. Since this memory is not owned by you, the OS terminated you.
Let's break this down a bit:
int *x = 0
this line creates a pointer called x and points it to NULL (or nowhere)
*x = 8
There is an immediate issue here as soon as you "dereference" x, meaning asking for the spaces associated what x points to.
Since you pointed x at NULL you're asking for the int located at NULL. This is illegal as NULL is an invalid memory space causing a seg-fault.