c++ Insert in array algorithm malfunctioning - c++

#include <iostream>
using namespace std;
/* This code is not working as it does not insert the value of item in the
array instead the value of item is zero. But i have troubleshooted this
problem and figured out that the code works fine if i define "int item" as
constant variable or use int i as global variable instead of defining in the
for loop. so my question is what is the reason behind this malfunctioning or
is there any programming secret i haven't aware of yet*/
int main()
{
int LA[] = {1, 3, 64, 98, 54};
int k = 3;
int n = 5;
int item = 46;
int j = n;
for(int i = 0; i < n; i++)
{
cout << "LA[" << i << "] = " << LA[i] << endl;
}
n++;
for( ; j >= k; j-- )
{
LA[j+1] = LA[j];
}
LA[k] = item;
cout << endl << "After insertion" << endl << endl;
for(int i = 0; i < n; i++)
{
cout << "LA[" << i << "] = " << LA[i] << endl;
}
return 0;
}

LA has a fixed size. It is a static array, and you cannot change the size in c or c++. Currently j will be 5 and you will attempt to access LA[5] which is outside the bounds of the array and Undefined Behaviour.
You have 3 options:
Reserve enough space in your static array to hold everything you need: LA[10] = {...
Use dynamic memory and resize: int *LA = new int[10]; (Look this method up)
The best, use a std::vector<int>.

If you wanna insert item as k'th element of array, You should know that the LA array has not 6th index (LA[6]). So before the second loop, initialize j with n-1.
Also if you wanna have all the values, You should use std::vector which can add the values and indexes, dynamically.
For further studies about vectors see this link: Here

Related

Memory leak when printing 2D array

I have memory leak when i print my 2D array, i looped in data from a vector into a vector called grid
Some indexes in Grid is null for example grid[8][8] is null, but grid[1][1] has a value of 3.
When i display indexes of grid with null value gives me a memory leak.
Below are my code, Any recommendations will be appreciated!
void populateAppendixB(vector<string> cityLocation, int **grid, int col, int row) {
vector<int> data = appendixB_data(cityLocation);
vector<string> appendixB_coordinates = getCoordinates(cityLocation);
vector<int> x_value = returncolValue(appendixB_coordinates);
vector<int> y_value = returnrowValue(appendixB_coordinates);
//loop data into grid[][]
for (int i = 0; i < x_value.size(); i++) {
grid[x_value[i]][y_value[i]] = data[i];
}
cout << " ";
//Top outer Grid
for (int i = 0; i < col + 2; i++) {
cout << " # ";
}
cout << " # ";
cout << endl;
//end
//y-axis
for (int j = row; j >= 0; --j) {
cout << " " << j << " # ";
for (int i = 0; i <= col; ++i) {
//displaying data
if(grid[i][j] == 0) {
cout << " ";
}
else {
cout << grid[i][j] << " ";
}
}
//Right outer Grid
cout << "#";
cout << endl;
}
//Last row of #
cout << " ";
for (int i = 0; i < col + 2; i++) {
cout << " # ";
}
cout << " # ";
cout << endl;
cout << " ";
//x-Axis
for (int i = 0; i <= col; i++) {
cout << i << " ";
}
cout << endl;
}
You use grid[x_value[i]][y_value[i]] = data[i];, but will not fill all of the grid since you only fill in one value of each column of grid (you only do this loop: for (int i = 0; i < x_value.size(); i++) {). Unless the grid passed in is pre-filled in with 0's properly (impossible to tell given your submitted code), then this is probably undefined behavior.
Even if it is a pre-filled in 2d array, when you print the elements of grid, you iterate from [0, cols] and [0, rows], which is likely not what you want (that iterates cols+1 columns and rows+1 rows. So, at least that last value will be accessing memory that is probably not valid.
As previous comments mention, it's a better idea to just use std::vector (e.g. std::vector<std::vector<int>> while using .at(i).at(j) to access elements which make use of C++ exceptions rather than accessing bad memory) or even std::array which are better at preventing and catching many issues cleanly. If you're worried about speed, it's probably not a huge deal and you can avoid copies by e.g. passing by reference, wrapping things in smart pointers if applicable, move semantics, etc.
I solved my problem by setting all my 2D array values to { }, then populate the grid array with the values that i want specifically.
It solves the memory leak problem but i am not sure if it is a good practice.

Filling Dynamically Allocated Array in C++

I am trying to fill up the multi-dimensional array using dynamic memory allocation and running into problem of how to determine the size of each array.
The sizes are also dynamically generated in the for loop, not sure how i can transport this knowledge into looping construct to tell the compiler when to stop.
Please dont answer the problem directly, just a direction needed so i can figure out on how to solve the problem of determining this,
for (int v = 0; v < sizeof(a[y]); v++)
int** a = new int*[n];
for (int i = 0; i < n; i++) {
int colcount;
cout << "Enter Size of Array for " << i << " : ";
cin >> colcount;
a[i] = new int[colcount];
}
// How to fill the matrix now
for (int y = 0; y < n; y++) {
for (int v = 0; v < sizeof(a[y]); v++) {
cout << "Enter Array Content [" << y << "][" << v << "] :";
cin >> a[y][v];
}
}
Update:
Got it working by bringing the for loop inside.
int** a = new int*[n];
for (int i = 0; i < n; i++) {
int colcount;
cout << "Enter Size of Array for " << i << " : ";
cin >> colcount;
a[i] = new int[colcount];
for (int v = 0; v < colcount; v++) {
cout << "Enter Array Content [" << i << "][" << v << "] :";
cin >> a[i][v];
}
}
Last Update:
To better track contents and privileges of template class, i ended up using vectors and with the help of community, here is how i came up.
int n;
cout << "Enter Num of Vectors: ";
cin >> n;
vector<vector <int> > mult_arr(n);
for (int i = 0; i < n; i++) {
int k;
cout << "Enter size for vec " << i << ":";
cin >> k;
mult_arr[i].resize(k);
for (int x = 0; x < k; x++) {
cout << "Enter Array Contents [" << i << "][" << x << "] :";
cin >> mult_arr[i][x];
}
}
You cannot know or find the size of a dynamic allocated array without actually holding the size in a variable. You can not use the classic sizeof(arr)/sizeof(type) to find the size because the sizeof() a pointer is just its type size and not the total array size. Use std::vector or keep tracking the sizes of each dynamic array.
Instead of using pointers to pointers to int, consider using a single allocation. It is easier and faster!
int * matrix = new int[width * height];
matrix[y * width + x] = 0;
delete [] matrix;
I took the liberty to rewrite your program to a more domatic C++ program (including a main function, so you can test it). Technically, this does solve the same problem, but instead of using new and delete, it uses std::vector, which should always be the first thing you should reach for.
Unless you have a very very good reason not to use vector, I advice you forget about new/delete. Know that it's there and get on with your life.
I realize this doesn't actually answer your question. I think it's too long for a comment so I'm providing it as answer instead.
#include <iostream>
#include <vector>
#include <string>
int get_an_integer(std::string message)
{
std::cout << message;
int n;
std::cin >> n;
return n;
}
int main()
{
std::vector<std::vector<int>> matrix;
matrix.resize(get_an_integer("Number of vectors:"));
for (auto& vector : matrix)
{
vector.resize(get_an_integer("Vector size:"));
for (auto& element : vector)
element = get_an_integer("Element value:");
}
for (auto v : matrix)
{
for (auto e : v)
std::cout << e << " ";
std::cout << '\n';
}
}
Notice how I don't have to keep track of anything and I don't really care about the explicit size of anything. Even the values of the elements aren't interesting.
I hope this helps you. If you have any questions, please ask.
You can memset to initialize an array. like
int *arr = new int[5];
fill(c, c + 5, 3); //fill(array, array+size, intialvalue)
cout<<c[4];
I hope this will help you.

Run Time Check Failure #2, AND array values swapped with outputs incorrectly

I've been struggling with this piece for a while now. I've googled run time check failure and I have no idea what to do. From what I get, it's because I declared swapEven and swapOdd to have an array of size 0? I initially had this set up as a pointer array, but that just didn't work. Can anybody point me in the right direction please? Thanks in advance!
void arrangeArrayJesseRagsdale(int* ary1, int* ary2, int arraySize1, int arraySize2) {
int i, j;
int temp;
int swap = 0;
int* swapEven = 0;
int* swapOdd = 0;
swapEven = new int[arraySize1];
swapOdd = new int[arraySize2];
cout << " Original Arrays\n Array #1: ";
for (i = 0; i < arraySize1; i++) {
cout << ary1[i] << " ";
}
cout << endl << " Array #2: ";
for (i = 0; i < arraySize2; i++) {
cout << ary2[i] << " ";
}
cout << endl;
for (i = 0; i < arraySize1; i++) {
for (j = 0; j < arraySize2; j++) {
if (ary1[i] % 2 != 0) {
if (ary2[j] % 2 == 0) {
temp = swapOdd[i] = ary1[i];
ary1[i] = swapEven[i] = ary2[j];
ary2[j] = temp;
swap++;
}
}
}
}
cout << "\n Updated Arrays\n Array #1: ";
for (i = 0; i < arraySize1; i++) {
cout << ary1[i] << " ";
}
cout << endl << " Array #2: ";
for (i = 0; i < arraySize2; i++) {
cout << ary2[i] << " ";
}
cout << endl;
if (swap > 0) {
cout << "\n Swapping info -\n";
for (i = 0; i < swap; i++) {
cout << " Array #1 value " << swapOdd[i] << " swapped with Array #2 value " << swapEven[i] << endl;
}
}
cout << "\nThere is/are " << swap << " swap(s)." << endl << endl;
delete[] swapEven;
delete[] swapOdd;
return;
}
First, your arrays here:
int swapEven[] = {0};
int swapOdd[] = {0};
Have 1 element each.
Second, your loops use arraySize1 and arrraySize2 to index into the arrays above. There is no check whatsoever in your code to ensure that the indexing into these arrays are within bounds. More than likely, this is where your error occurs, and that is accessing the array out-of-bounds.
If your goal is to create arrays with the same number of elements, use std::vector:
#include <vector>
//...
std::vector<int> swapEven(arraySize1, 0);
std::vector<int> swapOdd(arraySize2, 0);
The rest of the code stays the same.
swapEven and swapOdd do not have zero size, they are arrays containing the single integer element, 0. These arrays therefore have length 1.
However, from what I can tell from your code, you need to declare swapOdd to have at least as many elements as does ary1. Similarly, swapEven needs to have at least as many elements as does ary2. This is because you are storing values in those arrays using the indices of ary1 and ary2. Writing to unallocated memory may cause the crash that you see.
Also use of the indices of the 2 arrays will result in non-contiguous storage of the swapped values in swapOdd and swapEven. The affect of this is that the swap reporting code will use the wrong array elements when generating the report.
You might be better off using a dynamic "list" data structure for accumulating the swapped elements. C++ has a few alternatives there such as list and vector and these could be used instead of the swap arrays.
One other thing, rather than use pointer arithmetic to access the elements of arrays ary1 and ary2, it's more readable to use array indexing, i.e.
ary[i]
instead of
*(ary1 + i)

Using pointer arithmetic to add the contents of two arrays and save to an empty array

So I have written a function that should simply add the values of each element stored in two separate arrays, and save them to a third array.
I don't understand what the issue is, I am simply adding together the value of the int stored at the location referenced by each of my pointers, and saving it to my third, empty, array.
My code compiles just fine, but when I loop to print the contents of my third array (which should contain the sum of the two previous arrays elements at their respective indexes) it just prints a bunch of memory addresses. What gives?
EDIT: I fixed my while loop to perform the arithmetic, and everything is working well. My working code is below. Hope it helps someone else.
#include<iostream>
#include<stdlib.h>
using namespace std;
void arrayAdd(int firstArray[], int secondArray[], int targetArray[], int size){
int *firstPtr = firstArray;
int *secondPtr = secondArray;
int *tragetPtr = targetArray;
while (firstPtr <= &firstArray[size - 1] ){
//add the first two array elements
*tragetPtr = (*firstPtr + *secondPtr);
// point to the next location
*firstPtr++;
*secondPtr++;
*tragetPtr++;
}
}
int main() {
int totalElements;
const size_t ARRAY_SIZE = 50;
int firstIntegerArray[ARRAY_SIZE];
int secondIntegerArray[ARRAY_SIZE];
int thirdIntegerArray[ARRAY_SIZE];
cout << "Please enter the total number of elements for your array: ";
cin >> totalElements;
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the first array at index " << i << ": ";
cin >> firstIntegerArray[i];
}
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the second array at index " << i << ": ";
cin >> secondIntegerArray[i];
}
//run our arrayAdd function
arrayAdd(firstIntegerArray, secondIntegerArray, thirdIntegerArray, totalElements);
cout << "The conents of your two arrays added together is; " << endl;
for(int i = 0; i < totalElements; i++){
cout << thirdIntegerArray[i] << ", ";
}
return 0;
}
A local array decays to a pointer when it is passed to a function, so you can't use sizeof on it anymore. Indeed this:
void arrayAdd(int firstArray[]) {
int *firstPtr = firstArray;
std::cout << "sizeof(firstArray) == " << sizeof(firstArray) << std::endl;
std::cout << "sizeof(firstPtr) == " << sizeof(firstPtr) << std::endl;
}
int main() {
int test[] = {1,2,3,4,5,6,7,8,9,0};
arrayAdd(test);
return 0;
}
Prints:
sizeof(firstArray) == 8
sizeof(firstPtr) == 8
on my 64 bit machine.
Casting int[] to int* doesn't change anything since it already became a pointer as an argument. You should pass the size of the array to the method or, since you are working with C++, use an std::array or std::vector which will just solve any problem.

Populating an array

Can you help me with a problem on populating an array of 5 circles with random numbers.
The random number would be the radius of the circles.
Here is my code:
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
// Array 2, below section is to populate the array with random radius
float CircleArrayTwo [5]; // store the numbers
const int NUM = 5; // Display 5 random numbers
srand(time(NULL)); // seed the generator
for(int i = 0; i < NUM; ++i)
{
CircleArrayTwo[i] = rand()%10;
}
cout << "Below is the radius each of the five circles in the second array. " << endl;
cout << CircleArrayTwo << endl;
system("PAUSE");
return 0;
}
Currently is output the following:
Below is the radius each of the five circles in the second array.
002CF878
Where am I going wrong?
Any help is much appreciated
You are printing the address of the first element of the array.
You could loop over the array and print each element:
for(int i = 0; i < NUM; ++i)
{
std::cout << CircleArrayTwo[i] << ", ";
}
std::cout << "\n";
Or, if you have C++11 support,
for (auto& x : CircleArrayTwo) {
std::cout << x << ", ";
}
std::cout << "\n";
The way you populated the array is correct, however you cannot print an array like that. You need to write a loop to output the values one by one.
In C(and C++) arrays are almost equivalent to pointers to the beginning of memory location. So you're just outputting the adress of the first element;
To output all elements introduce another loop:
for(int i = 0; i < NUM; ++i)
{
cout << CircleArrayTwo[i] << endl;
}
CircleArrayTwo is a pointer. When you print a pointer, it prints a memory address, like the one you provided. In order to print the values of an array, you need to use the [] notation that you have for the insert.
You could loop over the values in the array and print each one:
for (int i = 0; i < NUM; ++i) { cout << CircleArrayTwo[i] << endl; }