How to dereference an array element (C++) [closed] - c++

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 8 years ago.
Improve this question
I wanted to create an array of a specific size using a variable, but allegedly the only way to do that is to use pointers.
int size = 5;
string* myArray = new string[size];
I now want to assign an element from this array to another variable, which I believe will only work through dereferencing. The following line of code doesn't work. How do I fix it?
string line;
myArray[0] = "Hello";
line = *myArray[0];
Edit:
I just want to clarify something: Using the normal "myArray[0]" code doesn't work either. It compiles, but causes a crash. Here's some more specific code regarding what I want to do.
void MyClass::setLine(string line)
{
myLine = line; /*This is a private variable in MyClass*/
}
///////////////
MyClass* elements = new MyClass[size];
elements[0].setLine(myArray[0]);
I want to assign the array element to a private variable from a class, but the program crashes when I try to assign the value to the private variable.

If you know the size at compile time, you can use a normal array. If you only know the size at runtime, you could still use a std::vector, which is far easier to use than manual allocation.
Anyway, if you really want to learn about pointers for array managing, keep in mind that the index operator is equivalent to addition and dereference, i.e. ar[i] is the same as *(ar + i). In other words, indexing is just dereferencing at an offset.
As such, no extra dereference is needed. Just drop the asterisk in the failing line.

Valid code will look like
string line;
myArray[0] = "Hello";
line = myArray[0];
By the way you could use class std::vector instead of the array if you are going to add or remove elements from the collection.
For example
std::vector<std::string> myArray;
myArrray.reserve( 5 );
myArray.push_back( "Hello" );
line = myArray[0];

Related

Why does the data still exist after I delete the space of the array? [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 3 months ago.
Improve this question
Today, I found a small problem when creating dynamic arrays.
I use the resize () function to change the size of the array. In the resize () function, I created a temporary array "newData", and then I assigned it the new size I wanted. After assigning the value of the initial array "Data" to it, I set
Data=newData;
At this time, the task of the resize () function has been completed. Before exiting the function, I had a whim and deleted the space of "newData" by
delete [] newData;
After that, when I output the value of Data [2], I can still output the value.
Now I'm a little confused. "Data" and "newData" should be pointers, right? When I use the statement "Data=newData;", what "Data" points to should become the address space that "newData" points to. If I delete the address space of "newData", shouldn't the space corresponding to "Data" also disappear? Why can I continue to output values?
The following is the complete code
#include<iostream>
using namespace std;
int Length = 0;
int* Data;
void resize(int,int *);
int main()
{
Data = new int[5];//This is the space I allocated for the initial array
for (int i = 0; i < 5; i++)
Data[i] = i;
Length = 5;//There are five data in the initial array
int newLength = 10;//I started distributing new sizes to the initial array
resize(newLength,Data);
cout << Data[2];//The output is still 2
}
void resize(int newLength,int *Data)
{
int* newData = new int[newLength];//A temporary array
for (int i = 0; i <Length; i++)//Move the value of the original array to the temporary array
{
newData[i] = Data[i];
}
Data = newData;
delete[] newData;//Delete the space where the temporary array is located
}
You (try to¹) access deleted space; that's what is called undefined behaviour in C++: Anything might happen. There might be the original values, the might be some other data you worked on put there, there might be the value 0xdeadcafe all over the place, your program might crash or cause a fire, delete all files or give an attacker access.
It's undefined, and you found one of the things that might happen.
¹ From your question, that was your intent. Luckily, you messed up your resize function prototype, and pass in the Data pointer by value, not by reference, so that your Data = newData; doesn't do anything outside your function. That together with the global variables on top of your files: Maybe revisit what a function is and what scope and pass-by-reference mean!
Generally, you're a C++ beginner: cool! That's a good path to be on.
Maybe do less with new and delete. It's been a while since I used these two, they're becoming a rare pattern in modern C++! C++ can very well (for the most part) be written without these, completely, by using other methods, where your memory allocation and deallocation are linked to objects' lifetimes. And that's way less error-prone, and honestly, easier to understand.
For example, in your use case, instead of your Data, newData, new and delete handling, you could have said std::vector<int> Data(Length);, have put the values in exactly as you did, and then just called Data.resize(newLength);. No need for manually knowing where to delete your memory!
I'm not sure why you're doing this, but you're declaring your variables globally. That's a bad idea from start to finish, so, um, just don't do that: Declare variables in the scope you need them, which would be your main function. Maybe someone who has had a very early 1970's copy of some C book confused obsolete C with the C++ you should be taught? I don't know. Global variables are generally a bad idea.

coping an array from one object to another object [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 2 years ago.
Improve this question
set &set::operator=(set const &s) {
elems = new int[s.num_elems];
num_elems = *(new size_t);
for (size_t i = 0; i < s.num_elems; i++) {//i am getting error in this line on "=" saying " a value type int* cannot be assigned tpo an entity of type int".
elems[i] = &(s.elems[i]);
}
num_elems = s.num_elems;
return *this;
};
i am trying to copy an object to another object they each has two private size_t num_elems and int *elems.i have tried changing the pointer symbols and copying the array directly but it gives me error everytime
This line is bad: num_elems = *(new size_t);
It just leaks a few bytes and does nothing useful. Delete it.
Then there is a problem where you are assigning the address of s.elems[i] into elems[i]. Which is not right because elems[i] is an integer, and the address of s.elems[i] is... well, an address.
So you need to change this line: elems[i] = &(s.elems[i]); to this: elems[i] = s.elems[i];
A few tips:
& this is called the "address of" operator. It gets the address of where something is in memory.
* this is called the "pointer dereference" operator. It helps you access what the pointer is pointing at.
When you access an array with square brackets, like this: elems[i] you're de-referencing it. Which means you're using the value that the pointer is pointing at. It's the same as doing this: *(elems + i)
Study your pointers :D They're a little tricky at first but they get easier with time and practice.

C++ pointer to entire array. Memory deallocation [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 7 years ago.
Improve this question
On one of the forums I found a way to create a pointer to an entire array , rather than the first value . But how to initialize and access the array elements ?
Here is code of declaration:
char (*p)[7];
When I'm trying to free memory I get (_BLOCK_TYPE_IS_VALID(pHead->nBlockUse) error on line:
delete[] p;
How to fix it? I read that I need correct initialization with 'new'. But how to initialize it with 'new'?
I don't know if I understand good your problem. You said create a pointer to an entire array, but every time you declare an array with fixed length in c/c++, the variable points to the begin of the allocated memory. In other words, the variable stores the memory address where the array starts.
So, if you write char p[7], you can get, for example, the third value in two different ways: p[2] or *(p + 2) . But, in this case, you can not use delete, because the variable has a statically memory allocation.
If you want to use delete, you have to create a dynamic array with the follow code:
char *p;
p = new char[7];
// using p var
delete[] p;
In the other side, with the statement char (*p)[7], p is a pointer to the the variable that stores the first memory address of a fixed length array. In this way, you can not delete the fixed memory with the statement delete p, delete (*p) etc. To use delete in this case, you would have to allocate the memory dynamically like the example I wrote above:
char **p, *a;
a = new char[7];
p = &a;
// use ..
delete *p;
I hope it was useful :)

Passing a LPDWORD as out parameter [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am new to C++ and I need to create a function with this structure:
BOOL myfunc(LPDWORD myLpdword){ // myLpdword must be an out parameter
DWORD myDword = 1;
myLpdword = &myDword;
return true;
}
int main(){
DWORD outDword = 20;
myfunc(&outDword);
cout << outDword << end1;
return 0;
}
I expected that the value of outDword would be 1 (changed by myfunc), but the value is not changed by myfunc.
Please, can you give me a hint to solve this problem?
Like this
BOOL myfunc(LPDWORD myLpdword){ // myLpdword must be an out parameter
*myLpdword = 1;
return true;
}
Out parameter is not something that means anything in C++. MS use it but only because they are using a consistent terminology across different languages.
In C++ terms what you did is pass a pointer to the variable you want to modify to myfunc. What the above code does is take that pointer and dereference with the * operator it to modify the variable you wanted modified.
I like that you're writing small test programs to check your understanding of C++. But as others said there's no real substitute for a decent book. Any C++ book is going to cover this.
You passed in a pointer to outDword.
myLpdword is now a pointer to outDword.
You then changed myLpdword to be a pointer to myDword.
You never did anything with the VALUE of outDword.
You assigned the pointer of a variable that will not exist after exiting the function body (read on scopes in C/C++.
To solve your problem, assign the value of the variable to the dereferenced pointer, like so: *myLpdword = myDword;. It would also be wise to check that the value of the pointer is not null before dereferencing it like this: if (myLpdword == 0) { return; } . This check doesn't guarantee that the pointer is safe to assign to, but Atleast guards you against null pointer access.
In C++ this is called pass-by-reference. You denote it with an ampersand in the function signature:
bool myfunc(DWORD &myDword) {…
The ampersands you are using now are actually getting the address of the variables, so you should remove those.

C++ How to resize a dynamic array without losing data? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to resize a dynamic array without losing data.
Like this:
double * pVecDin;//POINTER
int num_values = 2;
pVecDin = new double[num_values];
pVecDin[0]=5;
pVecDin[1]=6;
int new_num_values=4;
pVecDin = new double[new_num_values];
//Next I lost value of pVecDin[0] and pVecDin[1]
pVecDin[2]=8;
pVecDin[3]=9;
Do I need make an Auxiliar Dynamic Array to copy the old values?
Like:
int new_num_values=4;
double * pVecDin_aux; //POINTER
pVecDin_aux = new double[new_num_values];
pVecDin_aux = pVecDin;
for(int i=0; i < n; i++)
{
pVecDin_aux[i] = pVecDin[i];
}
Make a new, empty array with the new desired size.
Copy everything in the old array to the new array.
Delete the old array.
Assign the pointer of the old array to the address of the new array.
Or use a vector.
As nhgrif has mentioned, you need to make copy of the array.
There is another way if you can use malloc for memory allocation, then you can use realloc for resizing the array.
There are better ways as suggested by other like to use std::vector or list.