I am trying to create an array of Object pointers in order to sort some data. Here is my code:
ArrayClass<Exoplanet*> exoplanets;
int count = 0;
for (int i = 0; i < exosystems.size(); ++i) {
ArrayClass<Exoplanet> *temp = exosystems.at(i)->getPlanets();
for (int k = 0; k < temp->size(); ++k) {
exoplanets.add(&temp->at(k));
}
temp->~ArrayClass();
}
//check to see if pointer array is working properly
for (int i = 0; i < exoplanets.size(); ++i) {
exoplanets.at(i)->printPlanet();
cout << endl;
}
ArrayClass<Exoplanet> *Exosystem::getPlanets(void) const
{
return planets;
}
Also the getPlanets() function is included at the end for reference. Whenever I print the planets in the last for loop, all of the exoplanet pointers point to the last exoplanet returned from the getPlanet() function the final time through the 1st for loop. I think this has something to do with exoplanets.add(&temp->at(k)), but I am not sure how to fix it. Thanks in advance
Related
I'm writing a simple program within which a dynamic array is to be created. The function that is being used to create said array is in a second .cpp file, attached as a user-made library. Unfortunatelly Visual Studio pops an error saying that the program can't use uninitialized variable. I feel like it's a really easy problem to solve, but I don't know how to get through it. Here is the code:
int main()
{
int i = 5, j = 6;
string** Array;
createDefStruct(Array, i, j);
/*for (int k = 0; k < i; k++)
{
for (int m = 0; m < j; m++)
{
Array[i][j] = "YIKES";
cout << Array[i][j] << '\t';
}
cout << endl;
}*/
deleteDefStruct(Array, i);
return 0;
}
The createDefStruct function:
void createDefStruct(string** Arr, int varAttribCount, int varCount)
{
Arr = new string * [varAttribCount+1];
for (int i = 0; i < varAttribCount+1; i++)
Arr[i] = new string[varCount];
}
How do I go about initilizing a variable?
Thank you in advance!
So the problem is that instead of returning your array from the function you passed the array into the function as parameter. This mean that the variable is uninitialised in main (even though it is initiialised in createDefStruct). Rewrite like this
string** createDefStruct(int varAttribCount, int varCount)
{
string** Arr = new string * [varAttribCount+1];
for (int i = 0; i < varAttribCount+1; i++)
Arr[i] = new string[varCount];
return Arr;
}
int main()
{
int i = 5, j = 6;
string** Array = createDefStruct(i, j);
...
In general when you want a function to return a value you use return from inside the function to return that value. When you want to pass a value into a function you use a parameter. In your createDefStruct function varAttribCount and varCount are the parameters but the array should be a return value.
I have a class called ContactInfo and is structured as written below:
class ContactInfo
{
private:
string contactName;
string contactNumber;
public:
ContactInfo()
{
contactName = "";
contactNumber = "";
}
//setter and getters
};
and I have a function that creates an array of ContactInfo and populates it via user input. After populating the array it would be passed to another function that would sort it, the said function is written as shown below.
void sortListByName(ContactInfo contactList[], int listSize)
{
for(int i = 0; i < listSize; i++)
{
for(int j = i+1; j < listSize+1; j++)
{
if(contactList[i].getContactName() > contactList[j].getContactName())
{
ContactInfo temp = contactList[j];
contactList[i] = contactList[j];
contactList[j] = temp;
}
}
}
}
The main method
int main()
{
...
int n;//array size
ContactInfo *newList = contactList(n);//populates the array.
sortListByName(newList, n);
...
}
The problem is that the program would terminate before the sorting would happen and produce the error:
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Look at the upper bound of your inner loop. Notice that we can have j equal to the size of the array for the last iteration.
In C++, an array of size N has its elements indexed from 0 to N-1. In your case, you're trying to access an element past the end of the array, and are running into Undefined Behaviour. Ensure your index is within the bounds of the array.
Secondly, you should be using std::vector over raw arrays wherever possible anyways.
Third, the standard library provides the std::sort algorithm for you, which will almost always be faster than the bubble sort that you have implemented.
Your error is made in sort algorithm in the last iteration.
The thing is, that in first for loop variable i goes from 0 to listSize,
and in second for loop variable j goes from i+1 to listSize+1. When variable i reaches listSize-1, variable j will start from i+1 in the second for loop. This means j=listSize, and then when you try to access contactList[j] an error is going to occur because elements of contactList start from index 0 and end with index listSize-1.
void sortListByName(ContactInfo contactList[], int listSize)
{
for(int i = 0; i < listSize; i++) //it should be for(int i=0;i<listSize-1;i++)
{
//here is your mistake. When i = listSize-1 then j=listSize and
// that index is out of range.
for(int j = i+1; j < listSize+1; j++) //it should be for(int j=i+1;j<listSize;j++)
{
if(contactList[i].getContactName() > contactList[j].getContactName())
{
ContactInfo temp = contactList[j];
contactList[i] = contactList[j];
contactList[j] = temp;
}
}
}
}
this is how your code should look like:
void sortListByName(ContactInfo contactList[], int listSize)
{
for(int i = 0; i < listSize-1; i++)
{
for(int j = i+1; j < listSize; j++)
{
if(contactList[i].getContactName()> contactList[j].getContactName())
{
ContactInfo temp = contactList[j];
contactList[i] = contactList[j];
contactList[j] = temp;
}
}
}
I'm trying to create two dimensional array and assign objects into it. What's important is, that I want to do this using POINTERS. I want to achieve it like this:
Create pointer which will point to array of pointers.
Having array pointers I create next 10 cells in memory for example to store there individual object.
This is my code:
I create basic pointer for storing the address for array of pointers:
SpecialPoint **arrayOfPointsOnTheMap = NULL;
Next I initialize this array:
arrayOfPointsOnTheMap = new SpecialPoint*[size];
And then create cells in memory:
for (int i = 0; i < szer; i++) {
arrayOfPointsOnTheMap[i] = new SpecialPoint[wys];
}
And for the end I want to assign object to this newly created array:
SpecialPoint *pontInTable;
for (int i = 0; i < szer; i++) {
pontInTable = arrayOfPointsOnTheMap[i];
for (int j = 0; j < wys; j++) {
pontInTable[j] = new SpecialPoint();
}
}
But I get error when trying to create new object int array. I'm a little confused about it. Can anyone help?
What you want to do in the assignment part is not very clear so I will answer based on my best guess. Let`s say your class is as follows:
class SpecialPoint
{
public:
int x;
int y;
SpecialPoint(int xx, int yy)
{
x=xx;
y=yy;
}
SpecialPoint()
{
x=0;
y=0;
}
};
Then you can use the following code to create and initialize your 2d array:
int size = 4;
int wys = 3;
SpecialPoint** arrayOfPointsOnTheMap = new SpecialPoint*[size];
for(int i = 0; i < size; i++)
{
arrayOfPointsOnTheMap[i] = new SpecialPoint[wys];
} // you have your array at that point
SpecialPoint fakePoint(5,6); // create a special point
for(int i=0; i < size; i++)
{
for(int j=0; j < wys; j++)
{ // Assign your special point instance to all the array cells.
arrayOfPointsOnTheMap[i][j] = fakePoint;
}
}
After you are done with the array, do not forget to clean memory using:
for(int i = 0; i < size; i++) {
delete [] arrayOfPointsOnTheMap[i];
}
delete [] arrayOfPointsOnTheMap;
Good luck!
I am using following code in c++
#include <iostream>
using namespace std;
int functionIs();
int main()
{
functionIs();
return 0;
}
int functionIs()
{
int value[3];
value[0] = 0;
for (int i = 0; i < 3; i++)
{
value[i] += i + 1;
}
for (int k = 0; k < 3; k++)
{
cout << "Value = " << value[k];
cout << endl;
}
return 0;
}
Output:
Value = 1
Value = 2
Value = 4197152
What is wrong?
Thank you in advance.
You need to assign a value to every element in array value. You are only giving the first element the value 0:
Value[0] = 0;
If not you add to whatever was in memory at location value[i] whit this code:
Value[i] += i + 1;
I think you are trying to add one to the previous value in the array, not add i+1 to each value in the array. Try changing the first loop to:
value[0]=0;
for (int i=1; i<3; i++) {
value[i] = value[i-1]+1;
}
Accessing uninitialised variables is undefined, as already stated in comments. The easiest to initialise all the elements of an array to zero would be
int value[3] = {};
Aside: When i going to be changing for every iteration and the element assigned is going to change every time, why use +=, you can just assign = and be done with it.
i have to implement a small and simple game in c++ (a maze) and I have some problems right now.
Some snippets:
I've got an array of object pointers which represents my fields in the maze
Field*** maze;
init of the maze:
for (n = 0; n < MAZE_WIDTH; n++) {
this->maze[n] = new Field*[MAZE_HEIGHT];
for (p = 0; p < MAZE_HEIGHT; p++) {
this->maze[n][p] = new Field();
this->maze[n][p]->x = n;
this->maze[n][p]->y = p;
}
}
When creating the maze i need a list of already visited fields and a stack
so I did:
std::vector<Field*> visited;
std::vector<Field*> stack;
Then later I want to put a Field* into my stack
stack.push_back(neighbour);
But after this push all values in the object are wrong.
Even if i try
neighbour = stack.back();
all the values are completly different
I already red some threads about this topic and that's why i chose a vector of pointers and not objects.
Where is my fault?
Edit:
Some more snippets as requested:
Of course I allocate memory for the mate itself
this->maze = new Field**[MAZE_WIDTH];
Field is a simple class which looks like:
class Field {
public:
Field();
~Field();
bool w_left;
bool w_right;
bool w_front;
bool w_back;
unsigned int x;
unsigned int y;
private:
};
Since, you didn't posted the code of how you are obtaining the values,
compare to this, and try to find your problem...
std::vector<std::vector<Field*> > maze;
// Ini
for(int i = 0; i < MAZE_WIDTH; i++)
{
maze.push_back(std::vector<Field*>());
for(int j = 0; j < MAZE_HEIGHT; j++)
{
maze[i].push_back(new Field());
maze[i][j]->x = i;
maze[i][j]->y = j;
}
}
std::vector<Field*> visited;
// push the field [4,5] in a visited vector
visited.push_back(maze[4][5]);
// Clean up
for(size_t i = 0; i < maze.size(); i++)
{
for(size_t j = 0; j < maze[i].size(); j++)
delete maze[i][j];
}
Why declare the maze as Field***?
The C++ alternative is std::vector<std::vector<Field*> > maze;, and that's what you should use.