C++ Pointing to a dynamically created memory [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 2 years ago.
Improve this question
Let me preface this by saying I am a c++ rookie, completely new and learning in school right now. One question I am stumped on is dynamically created memory and how to point back to it. For the assignment I have, I created the memory, printed in the console, then my task is to point back to dynamically created memory that I made at the beginning of the assignment. How do I do that? I must have to create a temporary variable or reference variable of some sort, but I'm just unsure of how to.
// Task 1
//int *p;
int j = 18;
int *p = new int(2);
cout << "Dynamically created integer: " << *p << endl;
*p = j;
cout << "Named integer: " << *p << endl;
cout << "Return to dynamically created integer: " << *p << endl;
delete p;
That second to last line where I have the *p, that is incorrect, I just need to point back to the 3rd line of code somehow. Thank you!

You have a slight misunderstanding of how pointers work. We'll correct it here.
*p = j;
You think that this changes p to point to j. It does not. But let's proceed.
cout << "Named integer: " << *p << endl;
You are now thinking that this shows what p is pointing to now. And on the next line you want p to point to what it was, before.
Except that p is always pointing to the same thing, all the time. This line:
*p = j;
This does not point p to j. This sets the value that p points to, to the value of j. This is a very subtle difference. To change p to point to j, the correct syntax would be:
p = &j;
However, at this point, it becomes logically impossible to restore the original pointer. You have to save it first:
int *old_p=p;
p = &j;
Then, after you print what's p is pointing to now, you can simply restore it:
p=old_p;
And now the second print statement will show the original value that p was pointing to.

From my understanding, you're trying to get the memory location of j, for that you can use the "address of" ( & ) operator such as 'std::cout >> "memory address of j = " >> &j >> '\n';'

Related

Why are the two output results different? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 days ago.
Improve this question
int* p= NULL;
int** pp = &p;
cout << &p << endl;
cout <<*pp << endl;
I think the output results of the two should be consistent, but the first output is the address of p, and the second is 00000000. I want to know why.
You are mistaken, pp is the address of p
int** pp = &p; // set pp to the address of p
But *pp is the value of whatever pp is pointing at. In this case that is p which has a value of NULL.
The code is essentially no different to this
int x = 123;
int* px = &x;
cout << &x << endl; // print address of x
cout << *px << endl; // print value of x i.e. 123
The only difference being the type of the original value (int vs int*).
pp holds the address of p, so print pp, not *pp.

C++: How do I assign a value from a 2D dynamic array to another 2D dynamic array since 'temp[0][0] = array[0][0]' doesn't work? [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 3 years ago.
Improve this question
I'm new to c++, and I'm trying to figure out how to get a 2D dynamic array called temp to get values from another 2D dynamic array called array. I couldn't figure out how to assign any values from array to temp because the statement 'temp[0][0] = array[0][0];' doesn't seem to assign the value of array[0][0] which is 1 to temp[0][0]. Instead, temp[0][0] seems to have the same random number in it after 'temp[0][0] = array[0][0]' before any value was assign to temp[0][0]. I tried to assign temp[0][0] to 2 and it works. I don't really know how to exactly assign values from one 2d dynamic array to another. Anyway thanks in advance for helping me out!
...
//initializing first 2D dynamic array
int x=2;
int y=2;
int** array = new int*[x];
for(int i=0; i<x; i++) array[i] = new int[y];
//initializing second 2D dynamic array
int new_x=3;
int new_y=3;
int** temp = new int*[new_x];
for(int i=0; i<new_x; i++) temp[i] = new int[new_y];
//assigning values
array[0][0] = 1;
cout << array[0][0] << endl; //output is 1
//before assigning values to temp[0][0]
cout << temp[0][0] << endl; //out is a huge random number
temp[0][0] = array[0][0];
cout << temp[0][0] << endl; //output is the same huge random number
temp[0][0] = 2;
cout << temp[0][0] << endl; //output is 2
...
Memory under temp[0][0] is allocated dynamically, therefore that's why you're getting some random (garbage) stuff out of it before assigning 2. When you're assigning 2, the random garbage that's been there gets "overwritten" by a meaningful value, in your case 2 of int type
The code snippet you posted works exaclty as it should:
First cout prints 1 witch is the value of array[0][0].
Second cout prints the uninitialized temp[0][0], I compiled it here, and in this case the value is 0, but it could be anything.
Third cout prints 1 due to the assingment temp[0][0] = array[0][0].
Fourth cout prints the value of 2 assigned to temp[0][0].
If there are problems in your code it's not in the posted bit, aside from the fact that you are trying to print an unitialized variable in the second cout
I have tried running the code,and the output indeed is 1 after assigning the value.

c++ pointer and variable address switch of value, why?

I'm trying to modify a variable by a pointer, the problem is that they have the same address but the output is not right.
Here's the code:
int *ret;
int set = 56;
ret = (int *)&ret - 1;
*ret = 3;
cout << ret << endl << &set << endl << set <<endl;
The output is:
0x61ff08
0x61ff08
3
This look great, but what is really weird is that when I replace:
cout << ret << endl << &set << endl << set <<endl;
With this:
cout << ret << endl << set <<endl;
The output becomes:
0x61ff04
56
The pointer change of value and the set variable isn't modified though. It's like if I take out the &set of the cout the address pointed of the pointer exchange his address with the variable.
If I do this:
ret = (int *)&ret + 1; // instead of -1
The output becomes:
0x61ff0c
3
Can I have an explanation? I didn't find any documentation about this.
Can I have an explanation? I didn't find any documentation about this.
Main documentation in this case is C++ standard, though it is sometimes not to easy to find and comprehend information from there. So short version in your case - you can only subtract or add integers to a pointer when resulting pointer would point to an element in the same array or pointing to the fictitious element behind the last (in this case it is illegal to dereference your pointer). For this purpose single variable is treated like one element array (so for pointer to single variable you can basically only do pointer + 1). All other hacky tries to access variables through magic with pointer arithmetics are illegal and lead to Undefined Behavior.
Details about UB you can find here What exactly do "IB" and "UB" mean?
The answer was that the compiler is giving address by he's own way to the variable/pointers according to the code so the addresses can change, to fix this problem by only using addresses
instead of :ret = (int *)&ret - 1;
we can use :ret = (int *)ret - ((int)(ret - &set));
(i didn't want to use the basic ret = &set because i was trying to do it by manipulation only addresses)

Dynamic object creation of an array of pointers

I try to create objects dynamically. Each object is a pointer in an array of pointers. The compiler gives me
error C4700: uninitialized local variable 'villages' used.
And I can not figure out how to fix it. I would be very grateful to all the helpers.
int villageAmount;
cout << "Defining villages:\n\nEnter how many villages do you want: ";
cin >> villageAmount;
Village **villages;
for (int i = 0; i < villageAmount; i++)
{
cout << "\nDefining village's details #" << i + 1 << ":\n";
villages[i] = new (nothrow) Village;
}
Village **villages;
you declared villages without initializing, so it contains garabage valaue.
for (int i = 0; i < villageAmount; i++)
{
cout << "\nDefining village's details #" << i + 1 << ":\n";
villages[i] = new (nothrow) Village;
}
right below, you access into it and writes. That's no no.
If you want to store pointer of village (i.e. type of Village*) dynamically, you also need to allocate them.
Village **villages = new Village*[villageAmount];
Or if amount is fixed,
Village *villages[10] = { nullptr, }; // 10, 12344, or whatever
villages memory is never allocated, you should use a vector or any sort of container (an array look fine here).
If you really want to allow the memory manually you could do something like :
Village **villages = new Village*[villageAmount];
Don't forget to free EVERY new, (If you only free villages, all the Village* that he contain will remain allocated.
Edit : someone else answered so I guess my answere is usless

Constants and Pointers

This is going to be a long-winded post, so I apologize in advance.. but trying to ask multiple questions with context:
So, I've been trying to learn C++, and I've been picking everything up fairly easily, but I make a habit of trying to do things alongside the tutorials in "slightly different ways", in order to ensure that I understand the functionality of the thing I'm learning.
I seem to have hit a mental roadblock regarding constants and their involvements with pointers.
In the previous section, I think I got a pretty solid grip on references, dereferences (and the difference between * when used for dereferences and pointers), and then wrote this code:
int a[5];
int * p;
p = a;
cout << "Select the value for the first item at address(" << &a[0] << ")" << nl;
cin >> *p;
p++;
cout << "Select the value for the second item at address(" << &a[1] << ")" << nl;
cin >> *p;
p++;
cout << "Select the value for the third item at address(" << &a[2] << ")" << nl;
cin >> *p;
p++;
cout << "Select the value for the fourth item at address(" << &a[3] << ")" << nl;
cin >> *p;
p++;
cout << "Select the value for the fifth item at address(" << &a[4] << ")" << nl;
cin >> *p;
for (int n=0;n<5;n++)
cout << a[n] << "(" << &a[n] << ")" << nl;
Now, I realize that this isn't necessarily the most "optimized" solution, ever.. but it worked, I was able to "write" into the array I had store on the memory, and display the changes. It was neat, and like I said.. I think I got a pretty good understanding of how these things worked.
..and then, I hit the next section, which used the example:
const char * terry = "hello";
to teach me, and I quote: "As in the case of arrays, the compiler allows the special case that we want to initialize the content at which the pointer points with constants at the same moment the pointer is declared" (this being on the cplusplus.com tutorial).
Anyway, to get to the point: in order to try and familiarize myself with it and the previous section, I tried writing:
const char * p = "Hello.";
for (int n=0;n<5;n++)
cout << p[n] << "(" << &p[n] << ")" << nl;
cout << nl;
..and this does not work. I essentially tried replicating my previous code (although without the writing aspect) in an attempt to be able to read the RAM-location of each character in this constant array, and I experimented with every possible combination of pointers, references, dereferences, etc.. but I just get a print out of the whole "Hello." array with &p.
How in the hell does one get the reference of a constant array? I think I understand the basic premise that I'm creating an array and immediately allocating it to memory, and then assigning a pointer (p) to the first block ("H")'s location.. but I can't seem to print the blocks out. I was able to get the location of the first block to print at one point (can't remember what code I used to do this) and tied it into the for loop, but even then.. it just ALWAYS printed the location of the first block, even when assigned to follow the [n] count.
I have no idea what I'm missing, here, or if I'm just trying to reach "over my head", but maybe I just don't understand the usage/point of creating an array without being able to location the memory assignment of each item within it..
This brings me to my next issue, though. How does one get the memory location of a char variable, whether constant or not? I have been having issues with this code, as well:
char const a = 100;
int * b = &a;
cout << a << nl << *b << nl;
cout << nl;
Obviously, this doesn't work.. because I can't assign b to the location of a, since they're different variables.. and obviously making a char pointer is silly, since it's just going to print messed up/null characters instead of the location (I checked this, obviously.. not just assuming).
I hope I'm just missing an option to use which may just be "more advanced" than where I'm currently at.. but if I'm not, I don't quite see the point in being able to access the block location of any type of variable/constant, if you can't access ALL of them due to restrictions of the type being used.
This problem is sorta what limits the third quoted code, too: the fact that I can't just assign a variable to hold the &p value, since it itself would have to be a char to be compatible.. which is pointless since char can't hold the eight-digit reference.
In
const char * p = "Hello.";
[...] cout << &p[n] [...]
&p[n] is a pointer to char, and cout::operator<< has an overload that takes a pointer to a char and prints a null-terminated string, that's probably why you're confused.