Assigning value to the address pointed to by pointer? C++ [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 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

Related

How do I de-reference a pointer that is inside of an array using its index?

I am working on a stacks assignment in which we are creating a stack of pointers to structs called Data. Our professor is trying to help us develop good habits in regards to security in designing a program, which is why we have a stack of pointers to structs rather than a stack of the structs themselves.
I know that typically when de-referencing a pointer, you do it with an asterisk. Example:
int x = 5;
int* xptr = &x;
cout << *xptr << endl;
My understanding is that the above code would create a var x with the value 5, then a pointer that store the address of the var x, and then by printing *xptr, you are de-referencing the pointer, which causes the printed output to be the value of x (5). If I'm incorrect anywhere so far, let me know.
So now onto the stack class, my professor created the .h file for us and we have these attributes:
int top; // this is your top index
Data *stack[STACK_SIZE];
My understanding of the stack is that we have an array of pointers to Data structs (as indicated by the * prior to the name "stack") and the stack is literally named "stack". My question is: when I need to pop a Data struct off (I'm calling it popData) and I want to assign its value, I know that I can't just do popValue = stack[top] because popValue is of type Data, which can't receive an assignment of a pointer.
I was thinking I could do this:
Data popData;
*Data popDataPtr;
popDataPtr = stack[top];
popData = *popPtr;
I am thinking that logically this would work, but I was wondering if there is syntax for de-referencing the ptr and assigning it in the same line. I'm thinking either:
popData = *stack[top];
or
popData = stack[*top];
But I'm not sure what's correct. I can't seem to find an example online of this. Thanks in advance to anyone who can help.
I would recommend trying it next time by yourself to see which of your examples would work.
You can have the assignment in one line, and I would recommend also adding parentheses in complex expressions like this, so you don't have to memorize operator precedence:
Data popData = *(stack[top]);
Small comment regarding your other code, this will not compile:
*Data popDataPtr;
The syntax for a pointer to a Data is no different from a pointer to an int, which you had before:
int* xptr = &x;
So to make the code from your example work, you actually need
Data* popDataPtr;
There is a great rule of thumb in C++: read the declarations from right to left, for example:
Data * const ptr1; // ptr1 is a constant pointer to a Data
const Data * ptr2; // ptr2 is a pointer to Data which is const (or just to a constant Data)
Data * arr1[]; // arr1 is an array of pointers to Data.
popData = *stack[top]; // this will do the trick
Here you are accessing the pointer that you want and you are then dereferencing that pointer and storing the data pointed to in popData

Can i somehow access a value if i know its address? [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 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.

Use of Pointers - Very Confused! C++ [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 9 years ago.
Improve this question
I'm studying C++ using a few books, trying to learn SDL along side it. I understand that pointers "point" to a variable's memory address, and that they can be used to "reference" variables. But I don't understand their purpose? And how to use them properly?
I have a few examples from the book (I've added under the code that confuses me):
#include <iostream>
int main(void)
{
char string[6] = "Hello";
char* letter = string;
letter += 3;
OK, so there's a char pointer called 'letter' that points to the memory address of string. Then somehow we use the += operator on the pointer? How? What's going add? What are we adding the 3 to?
*letter = 'p';
And now here we use '*letter' instead of 'letter' - this means it's dereferenced, right? What does this actually DO?
string[4] = '!';
std::cout << string << '\n';
system("PAUSE");
return 0;
}
The rest of the code I understand.
Thanks for any answers!
George
EDIT: so let me get this straight - dereferencing a pointer (e.g. *pointer = 2;) is used to change the value of the variable (or array position, for that matter) when you want to?
EDIT 2: thanks to everybody's answers I almost completely understand the code I used as an example - however, I am still unsure as to the use of '&' (ampersand) in the context of pointers, and how/why they're used.
In this definition
char* letter = string;
letter is set to the address of the first element of character array string.
So *letter has value 'H'.
Let consider for example statement
++letter;
This statement "moves" the pointer to point to the next element of string. That is now the pointer points to the second element of string. Now the value pf *letter is 'e' because letter points to the second element.
Applying three times operator ++ as for example
++letter; ++letter; ++letter;
is equivalent to
letter += 3;
that is the pointer was moved three times and now it points to the second 'l' in string.
This statement
*letter = 'p'
will replace 'l' with 'p' and you will get that string now looks as
"Helpo"
After executing statement
string[4] = '!';
string contains
"Help!"
Instead of
string[4] = '!';
you could write
++letter;
*letter = '!';
Or you could combine these two statements in one statement
*++letter = '!';
EDIT: 'pointer' contains address of an object. When you write *pointer you access directly the object itself so *pointer = 2 change the object pointed by 'pointer'.
Also you should understand that if for example you have
int a[10];
int *p = a;
and let assume that the value of p (the address stored in p) is 4. Then expression ++p or p + 1 means that the pointer was "moved" to the next element of the array. It means that new value of p is not 5. The new value of p is p + sizeof( int ) that is 8 provided that sizeof( int ) is equal to 4.
In your example sizeof( char ) is always equal to 1 according to the C++ Standard.
You need a start from understanding pointers from beginning.
char string[6] = "Hello"; //string an array of 6 characters including null char
char* letter = string; //letter pointer pointing to string array,stores first char address
letter += 3; // Letter pointer in incremented by 3 char. Now it points to 4th char of string
*letter='p'; //replacing 4th char of string by p
cout<<letter; //prints "po";
Notes to help you
What are the barriers to understanding pointers and what can be done to overcome them?
Incrementing a pointer by an integer value (explained with an example):
Suppose you have int* x pointing to memory address 1000, and you increment it by 3: x += 3.
Variable x will now point to memory address 1000 + sizeof(int).
The size of int depends on your compiler; let's assume it is 4 bytes on your system.
So variable x is pointing to memory address 1012 (1000+3*4).
Now, suppose you use x in order to read the value at the memory address pointed by x:
int y = *x;
During runtime, the CPU will read 4 bytes from the memory address pointed by x, and store them into variable y, so that y will then contain the same value as the one stored in address range 1012-1015.
Then somehow we use the += operator on the pointer? How? What's going add? What are we adding the 3 to?
letter is in fact pointing to the first element of the string Hello. By adding 3 to it letter will point to the element 3 of the string (4th element).
And now here we use '*letter' instead of 'letter' - this means it's dereferenced, right? What does this actually DO?
Defreference means you are retrieving the value stored at the location letter points to.
ereferencing a pointer (e.g. *pointer = 2;) is used to change the value of the variable (or array position, for that matter) when you want to?
By doing *pointer = 2; you are storing 2 to the location pointer points to, ie, changing the value of the variable..

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.

Can two separate pointers reference the same address? If so, can I change the value at that address with either pointer?

So, I have this code fragment:
int * iPtr ;
int * jPtr ;
int i = 5, k = 7;
iPtr = &i;
jPtr = iPtr ;
I have just started learning about pointers, and need to get some doubts cleared.
is jPtr now essentially also pointing at i?
I know I can change the value of i by using *iPtr, but how can I change the value of the object being pointed to by jPtr?
How will changing the object being pointed to by jPtr affect the value of the object pointed to by iPtr, and i ?
1000 1001 1002 1004 --> address location ( note: just indicative)
----------------------------
| 5 | 7 | 1000 | 1000 |
| i | j | iPtr | jPtr |
-----------------------------
^^ | |
||________| |
|_________________|
iPtr=&i; --> iPtr points to i ==> address of i is stored in iPtr ==> *iPtr contents of i
jPtr=iPtr; ->jPtr points to i
Yep
jPtr is pointing to the same memory address as iPtr at the end of the given fragment. So, you can change i using *jPtr or *iPtr.
Since jPtr holds the memory address of i, if you change *jPtr, you are changing i and as a direct result, changing the value of *iPtr.
1: Yes, this is called pointer aliasing.
2: In the same way as you changed the value by using *iPtr, you can change the value of i by using *jPtr.
3: Since the pointers are aliased, meaning pointing to the same object, changing the value of the object that iPtr points to, also changes the value of the object that jPtr points to, because they're pointing to the same object.
jPtr has the same assignment as iPtr, so it isn't essentially pointing at i - it is.
The same way. *jPtr = x.
They are the same object. Pointers work by address, which means if you assign one pointer to an object and another to that pointer, they are both aimed at the same object.
At least, that's how I recall it. I'm just getting back into this stuff.
Yes
The same: *jptr=value;
If you change what jPtr points at (change the address it holds), it will not affect what iPtr points to. But as long as they point to the same thing, then changing the value (*jPtr=5) means the object pointed to by iPtr will also change
Yes
*jptr=42
Yes, it is the very same integer variable.
Question 1
Yes.
Question 2
*jPtr = ...
Question 3
It won't.