C++ array value printing inconsistent - c++

When I print the value of the 2D array "need", I'm getting two different results. While in the initialization loop, I print out all the array elements, as shown in the output section below. At need[0][0], the output is 7 (top right of output section, "need[i][j]:00 7").
Then outside the loop, I try to directly call this element, but this time need[0][0] returns 0.
This is for a Banker's algorithm assignment, where the resources are specified in a text file that is then parsed by my program. I think this is the only relevant code section. I'm sure this is some sort of pointers problem, but I have never been instructed on C/C++ programming and I'm just sort of figuring it out on my own.
// Initialize the need matrix
need = new int*[numProc];
for (int i = 0; i < numProc; i++){
for (int j = 0; j < numResources; j++){
need[i] = new int[numResources];
cout << " max[i][j]:" << max[i][j];
cout << " allocation[i][j]:" << allocation[i][j];
need[i][j] = max[i][j] - allocation[i][j];
cout << " need[i][j]:" << i << j << " " << need[i][j] << endl;
}
}
cout << "need[0][0]" << need[0][0] << endl;
This is the output:
max[i][j]:7 allocation[i][j]:0 need[i][j]:00 7
max[i][j]:5 allocation[i][j]:1 need[i][j]:01 4
max[i][j]:3 allocation[i][j]:0 need[i][j]:02 3
max[i][j]:3 allocation[i][j]:2 need[i][j]:10 1
max[i][j]:2 allocation[i][j]:0 need[i][j]:11 2
max[i][j]:2 allocation[i][j]:0 need[i][j]:12 2
max[i][j]:9 allocation[i][j]:3 need[i][j]:20 6
max[i][j]:0 allocation[i][j]:0 need[i][j]:21 0
max[i][j]:2 allocation[i][j]:2 need[i][j]:22 0
max[i][j]:2 allocation[i][j]:2 need[i][j]:30 0
max[i][j]:2 allocation[i][j]:1 need[i][j]:31 1
max[i][j]:2 allocation[i][j]:1 need[i][j]:32 1
max[i][j]:4 allocation[i][j]:0 need[i][j]:40 4
max[i][j]:3 allocation[i][j]:0 need[i][j]:41 3
max[i][j]:3 allocation[i][j]:2 need[i][j]:42 1
need[0][0]0

need[i] = new int[numResources]; should be before for (int j...
You could have avoided this by not using manual memory management, e.g.
std::vector< std::vector<int> > need(numProc, numResources);

i didn't read that carefully, but i saw your allocation
need[i] = new int[numResources];
it runs numResources*numProc times.

// Initialize the need matrix
need = new int*[numProc];
for (int i = 0; i < numProc; i++) {
for (int j = 0; j < numResources; j++) {
need[i] = new int[numResources];
The previous line is executed numResources times for each cell need[i]. Profligate leakage of memory.
Also, it gives you zeroed memory, so of course it prints 0.!!!!
cout << " max[i][j]:" << max[i][j];
cout << " allocation[i][j]:" << allocation[i][j];
need[i][j] = max[i][j] - allocation[i][j];
cout << " need[i][j]:" << i << j << " " << need[i][j] << endl;
Where are max and allocation defined?
}
}
cout << "need[0][0]" << need[0][0] << endl;

Related

How can I print 2D arrays with four columns

I am struggling with printing an array with 4 rows and 4 columns, when I initialized the array and entered all the values. Then, I used for loop to get all the values together so I can print them. But I get is an array that companied all the values in one row.
I have attached the output when I run the code.
Here is a portion of my code, it is long code but I am struggling in specific part:
#include <iostream>
using namespace std;
int main()
{
cout << "The martix before I flipped it: " << endl;
cout << endl;
int array[4][4] = { 16,3,2,13,5,10,11,8,9,6,7,12,4,5,14,1 };
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << array[i][j] << " ";
}
}
return 0;
The standard output utility std::cout is a stream from the stl and, as such, its << operator does not usually automagically append a linebreak.
Which is quite practical since, otherwise, you would not be able to print multiple numbers on a single line.
That being, said, you'll need to add the linebreak manually, like so :
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
Alternatively, you can consider printing lines 4 at a time since your matrix is of constant size :
for (int i = 0; i < 4; i++) {
std::cout << array[i][0] << " "
<< array[i][1] << " "
<< array[i][2] << " "
<< array[i][3] << " " << std::endl;
}
Have a great day,

What is happening with vector array here?

I'm solving the Traveling Salesman Problem via an ACO implementation in C++. However, I found out that the program I've built so far gives a segmentation fault.
(Note: I've limited the algorithm to only do one iteration of the colony for debugging purposes).
First off, I have a total of 52 cities taken from a file, and I distribute the ants so that every city has the same number of ants starting from it.
To store the distances between every pair of cities, I'm using a vector of vectors of doubles called Map (a square matrix). However, half-way during the execution it looks like these vectors are deleted. In this instance, it happens when calculating the path for the ant number 55. I've added a section of code just to highlight exactly where it crashes:
//DEBUGGING SECTION
cout << "Size Roulette: " << Roulette.size() << endl;
cout << "Size Remain: " << RemainingCities.size() << endl;
cout << "Size Map: " << Map.size() << " x " << Map[0].size() << endl;
int k = 0;
cout << "Test: Map access: " << endl;
for(int i = 0; i < Map.size(); ++i) // HERE IT CRASHES AT ANT NUMBER 55
cout << Map[0][i] << " ";
cout << endl;
cout << "Test: Operation: " << Map[Colony[ant_i][city_i-1]][RemainingCities[k]] << endl;
Roulette[k] = pow((MAX_DIST - Map[Colony[ant_i][city_i-1]][RemainingCities[k]]), heur_coef) + pow((pheromones[Colony[ant_i][city_i-1]][RemainingCities[k]]), pher_coef);
//END OF DEBUGGING SECTION
There, the function Map[0].size() normally returns 52 (just like Map.size(), as it's supposed to be a square matrix), but at the crashing iteration it returns what looks like a memory address, and the moment I try to access any element, a segmentation fault occurs.
I have checked that the memory access is always correct, and I can access any other variable without issue except Map until that 55th ant.
I've tried different seeds for the roulette method, but it always crashes at the same place.
I have also varied the number of ants of the colony. If it's just one ant per city, the program executes without issue, but for any higher amount the program always crashes at the 55th ant.
You can download the full cpp file and the reading .tsp file from github:
https://github.com/yitosmash/ACO
In any case, I'll leave the full function here:
void ACO(const vector<City>& cities, const vector<vector<double>>& Map, int max_it, int num_ants, double decay, double heur_coef, double pher_coef, double pher_coef_elit)
{
srand(30);
//Initialise colony of ants (each ant is a vector of city indices)
vector<vector<int>> Colony(num_ants, vector<int>(cities.size(), 0));
//Initialise pheromone matrix
vector<vector<double>> pheromones(cities.size(), vector<double>(cities.size(), 0));
//Initialise costs vector(for etilist expansion)
vector<double> costs(cities.size(), 0);
//Auxiliar vector of indices
vector<int> cityIndices(cities.size());
for (int i = 0; i < cities.size(); ++i)
cityIndices[i] = i;
//Longest distance from Map, used for heuristic values.
vector<double> longests(cities.size(), 0);
for(int i = 0; i < cities.size(); ++i)
longests[i] = *(max_element(Map[i].begin(), Map[i].end()));
const double MAX_DIST = *(max_element(longests.begin(), longests.end()));
longests.clear();
int i=0;
while(i<max_it)
{
for(int ant_i = 0; ant_i < num_ants; ++ant_i)
{
cout << "Ant: " << ant_i << endl;
//City for ant_i to start at; each ant is assigned a determined starting city
int starting_city = (int) ((float)ant_i/num_ants*cities.size());
//cout << starting_city << endl;
Colony[ant_i][0] = starting_city;
//Get a vector with the cities left to visit
vector<int> RemainingCities = cityIndices;
//Remove starting city from remaining cities
RemainingCities.erase(RemainingCities.begin() + starting_city);
//Create path for ant_i
for(int city_i = 1; city_i < Colony[ant_i].size(); ++city_i)
{
cout << "Calculating city number: " << city_i << endl;
//Create roulette for next city selection
vector<double> Roulette(RemainingCities.size(), 0);
double total = 0;
//DEBUGGING SECTION
cout << "Size Roulette: " << Roulette.size() << endl;
cout << "Size Remain: " << RemainingCities.size() << endl;
cout << "Size Map: " << Map.size() << " x " << Map[0].size() << endl;
int k = 0;
cout << "Test: Map access: " << endl;
for(int i = 0; i < Map.size(); ++i) // HERE IT CRASHES AT ANT NUMBER 55
cout << Map[0][i] << " ";
cout << endl;
cout << "Test: Operation: " << Map[Colony[ant_i][city_i-1]][RemainingCities[k]] << endl;
Roulette[k] = pow((MAX_DIST - Map[Colony[ant_i][city_i-1]][RemainingCities[k]]), heur_coef) + pow((pheromones[Colony[ant_i][city_i-1]][RemainingCities[k]]), pher_coef);
//END OF DEBUGGING SECTION
for(int j = 0; j < RemainingCities.size(); ++j)
{
//Heuristic value is MAX_DIST - current edge.
Roulette[j] = pow((MAX_DIST - Map[Colony[ant_i][city_i-1]][RemainingCities[j]]), heur_coef) + pow((pheromones[Colony[ant_i][city_i-1]][RemainingCities[j]]), pher_coef);
total += Roulette[j];
}
cout << endl;
//Transform roulette into stacked probabilities
Roulette[0] = Roulette[0]/total;
for(int j = 1; j < Roulette.size(); ++j)
Roulette[j] = Roulette[j-1] + Roulette[j] / total;
//Select a city from Roulette
int chosen = 0;
double r = (double) rand()/RAND_MAX;
while(Roulette[chosen] < r)
chosen++;
//Add chosen city to
Colony[ant_i][city_i] = RemainingCities[chosen];
RemainingCities.erase(RemainingCities.begin() + chosen);
}
cout << endl;
//Save cost of ant_i, for elitist expansion
costs[ant_i] = pathCost(Colony[ant_i], Map);
}
i++;
}
}
That part is very suspicious :
for(int i = 0; i < Map.size(); ++i) // HERE IT CRASHES AT ANT NUMBER 55
cout << Map[0][i] << " ";
because i is the size of the map but you use it as an index in a probable string / vector, so you probably go out of the string/vector with an undefined behavior
probably you want
for(int i = 0; i < Map.size(); ++i)
cout << Map[i] << " ";
or
for(int i = 0; i < Map[0].size(); ++i)
cout << Map[0][i] << " ";
As I said in a remark at a moment RemainingCities[0] values -163172699 first in
cout << "Test: Operation: " << Map.at(Colony.at(ant_i).at(city_i-1)).at(RemainingCities.at(k)) << endl;
so is not a valid index in Map, but there is visible reason to have that looking at the code, so the reason is a probable write out of a vector destructing your memory elements.
To detect where I replaced all the [...] by .at(...) and the first error I have is in ACO at the line
costs.at(ant_i) = pathCost(Colony.at(ant_i), Map);
where ant_i values 52 while costs has 52 entries and Colony 260, so the error concerns costs
note that ant_i is set by the loop
for(int ant_i = 0; ant_i < num_ants; ++ant_i)
and in that case num_ants value 260 so much more than the size of costs which is defined as
vector<double> costs(cities.size(), 0);
but cost is just allocated and set but never read, so its goal is just to destruct the memory.
If I remove the two lines concerning it I do not have anymore an error and the program ends normally, there is no exception in a .at(...) and valgrind detect no error too.

C++ Nested for loop for exponents with set base/exponent

So I need some help with this. I want to print out all integers between 2 and 2^20 that are integer powers of 2. I figured out that I need to increase the power by 1 each time but I can't seem to figure out what goes inside the inner for loop. I cannot use the pow() function
c = 2;
cout << "\nPROBLEM C" << endl;
for (int powerC = 1; powerC <= 20; powerC++) // powerC is exponent
{
cout << setw(5) << powerC << " ";
counterC++;
for (int x = 1; x <= 20; x++) // where I am having trouble with
{
c = (c*powerC);
cout << setw(5) << c;
} // end inner for loop
if (counterC % 8 == 0)
{
cout << endl;
}
}
cout << "\nNumber of numbers = " << counterC;
This is much simpler by using the << operator.
Since 2 is 2^1, you want to print all integers from 2^1 to 2^20 inclusively, or 20 numbers:
int c = 2;
for (int i=0; i<20; i++)
{
std::cout << c << std::endl;
c <<= 1;
}

In C++: How to overwrite an element to an array by moving entries below it up by one

I am trying to "delete" an element in my array. I have been told by those who know C++ better than I do that to accomplish this I must move all entries below the one I want to delete up by 1. Afterwards, I must decrease by 1 the variable keeping track of the size of the array. So I wrote this code to accomplish that:
cout << "Type the number of the inventory entry you would like to delete:\n";
cin >> entryToDelete;
for ( count = 0 ; count < (entryToDelete - 1) ; count++)
list[count] = list[count + 1];
position--;
I previously displayed for the user the entries in the array as #1, #2, #3, etc while their subscripts are 0, 1, 2, etc... That is why I put entryToDelete - 1. position is the variable that keeps track of the size of the array. Anyway, I use this code to output the array so I can check if the code worked:
for (int count = 0 ; count <= position ; count++)
{
cout << "Entry #" << (count + 1) << endl;
cout << "ISBN: " << list[count].ISBN << endl
<< "Author: " << list[count].Author << endl
<< "Title: " << list[count].Title << endl
<< "Quantity: " << list[count].Quantity << endl
<< "Price: " << list[count].Price << endl << endl;
}
For some reason, no matter what number I input to delete, the last element in the array is deleted. I have tried several modifications, such as changing the order of the array elements to modify: i.e. list[count + 1] = list[count], but this does not give me what I want.
Unfortunately, I am restricted from using vectors.
You need to move all elements to the right of that element one to the left.
Here is a simple code that shows how to move elements to the left
#include <iostream>
using namespace std;
int main() {
int arr[10]= {0,1,2,3,4,5,6,7,8,9};
int numToDelete = 5;
for (int i = numToDelete; i < sizeof(arr)/sizeof(arr[0]); i++ )
{
arr[i] = arr[i+1];
}
arr[sizeof(arr)/sizeof(arr[0]) - 1] = 0;
for(int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
{
cout << arr[i] << endl;
}
return 0;
}
This should do it. It moves all the elements into place and removes the entry you wanted to delete.
for ( size_t count = entryToDelete; count < arraySize - 1 ; ++count)
list[count] = list[count + 1];
--arraySize;
Move the entries following the deleted element to the front by one.

add results of a for loop after each iteration

I‘m having trouble with my for loop. I have a basic 2 times table that goes up from 1 to 10. (see below). I'm trying to add the result so that after every loop, allResult displays the values of all results added. it needs to show all results added after every loop. and I don't know how to go about it. A better description is the desired outcome commented in the code.
my Code...
int main(){
int allResult;
for( int i = 1; i < 11; i++)
{
int result = 2*i;
cout << 2 << " times " << i << " = " << result << endl;
// I want allResult to store results added. so after first loop, result = 2 so allResult = 2
// after second loop, result = 4. so allResult should be 6. (results from 1 and 2 added)
// after third loop, result = 6 so allResult should be 12. (results from 1, 2 and 3 added)
// I'm trying to apply this to something else, that uses random numbers, so i cant just * result by 2.
}
system("pause");
}
int allResult = 0;
for( int i = 1; i < 11; i++)
{
allResult += 2*i;
cout << 2 << " times " << i << " = " << 2*i << endl;
}
int allResult = 0;
for( int i = 1; i < 11; i++)
{
int result = 2*i;
cout << "2 times " << i << " = " << result << endl;
allResult += result;
cout << "allResult: " << allResult << endl;
}
int main()
{
int allResult=0;
for( int i = 1; i < 11; i++)
{
int result = 2*i;
allResult=allResult+result;
/*Initially allResult is 0. After each loop iteration it adds to its previous
value. For instance in the first loop it was allResult=0+2,
which made allResult equal to 2. In the next loop allResult=2+4=6.
Third Loop: allResult=6+6=12. Fourth loop:allResult 12+8=20 and so on..*/
cout << 2 << " times " << i << " = " << result << endl;
}
system("pause");
}