Having trouble with my C++ program. Involes resizing an integer array dynamically - c++

Here is what I have so far: http://cpp.sh/54vn3
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <cstdlib>
using namespace std;
int *reSIZE(int *&original, int &SIZE, const int &maxSIZE); //function prototype resize
void sortFUNC(int *&original, int &SIZE, const int &maxSIZE); //function prototype sortFUNC
int main()
{
int SIZE = 4; //size of current array
int maxSIZE = 10; //size of final array
int *original = new int[SIZE] {5, 7, 3, 1}; //old(current) array
cout << "Elements in array: "; //test output
reSIZE(original, SIZE, maxSIZE); //call function resize
cout << endl << endl; //blank line
cout << "Elements in array in increasing order: "; //test output
sortFUNC(original, SIZE, maxSIZE); //call function sortFUNC
cout << endl << endl;
return 0;
}
int *reSIZE(int *&original, int &SIZE, const int &maxSIZE)//function definition
{
int *temporiginal = new int[SIZE + 3]; //(final)new array
for (int i = 0; i < SIZE; i++) //copy old array to new array
{
temporiginal[i] = original[i];
cout << original[i] << setw(3);
}
delete[] original; //delete old array
original = temporiginal; //point old array to new array
return temporiginal;
}
void sortFUNC(int *&original, int &SIZE, const int &maxSIZE)
{
for (int i = 0; i < SIZE; i++)
{
int smallest = original[i];
int smallestINDEX = i;
for (int m = i; m < SIZE; m++)
{
if (original[m] < smallest)
{
smallest = original[m];
smallestINDEX = m;
}
}
swap(original[i], original[smallestINDEX]);
}
int *temporiginal = new int[SIZE + 3];
for (int i = 0; i < SIZE; i++)
{
temporiginal[i] = original[i];
cout << original[i] << setw(3);
}
delete[] original;
original = temporiginal;
}
I want to add a few elements at the end of the array in main, but when I do, the program crashes when I run it. The resize function that I created is supposed to expand the function in main to hold 10 elements. The one in main originally holds 4. The new array is supposed to change that to 10. How do I add three more integers to the array in main without it crashing? Is my resize function wrong? Or is it a problem in my main? The program that is shown right now works as is. But when I add another integer in the array in main, it crashes. Like, if I add a 2 after the 1.
Thanks.
Edit: I was able to add elements at the end of the array in main by adding them in the resize function.
cpp.sh/35mww
Like mentioned earlier, maxSIZE isn't being used. There are more useless stuff as well. I have to clean this up, but I figured out what I was trying to figure out. I don't know how to use structures yet. I know that there are a lot of different ways to write a program. I'm just a beginner.
Thanks, everyone.

You need to modify the value of size everytime you call the function rezise other wise even if u call the function resize 3 times u always will have SIZE+3 on your array size.After call resize try
original[4] = 0;
original[5] = 0;
original[6] = 0;
and after that try to do this.
original[7] = 0;
you should be able to see your mistake

Related

return a dynamically allocated array of the same length but with the elements in the reverse order

Write a function, reverseArray, that when passed an int array of length greater than 0 will return a dynamically allocated array of the same length but with the elements in the reverse order. For example, if passed the array, {1,2,3,4,5,6,7,8,9,0} the function would return the array {0,9,8,7,6,5,4,3,2,1}.
Below is my code, but there is a bug in it.
This is my output.
1
2
3
4
5
6
4113
6
5
4
3
2
1
0x7fffe697ceb0
The 4113 and address are provided by the compiler.
#include <iostream>
using namespace std;
int * readNumbers() {
int * a = new int[6];
for (int i = 0; i < 6; i++) {
int x;
cin >> x;
a[i] = x;
}
// a++;
return a;
delete[] a;
}
int *reverseArray(int *numbers1,int length) {
for (int i = length; i >=0; i--) {
cout << numbers1[i] << endl;
}
return numbers1;
delete [] numbers1;
}
int main() {
int *arr1 = readNumbers();
cout << reverseArray(arr1,6) << endl;
return 0;
}
I think there may have been an issue with your wording. Assuming you want your function just to print the reverse of a passed array, you're off to a good start.
One issue is what was said in the comments: your for loop is indexing past your array. When you type int * a = new int[6]; you are creating a pointer 'a' which points to a location in memory. Since you chose size 6, the appropriate amount of memory is allocated. If you happen to index outside of that range, you will end up pointing to a random spot in memory, not allocated for your array. Hence why you are getting a weird number '4113'.
A fix for this could be:
int i = length changed to int i = length-1
Another issue is that your function returns an integer pointer, and you are trying to cout this pointer. As another commenter said, you have to think about what this does. If you try this code:
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3};
cout << arr << endl;
return 0;
}
your output would be something like 0xff09ba. This represents the location of the start of the array in memory. If you change arr to (arr + 1) you will get the location of the second index of the array.
So when you type cout << reverseArray(arr1,6) << endl; you are really just printing out the location of numbers1 in memory. This is why you are getting '0x7fffe697ceb0' in your output. To fix this, simply make your function
void reverseArray(int *numbers1,int length) {
for (int i = length; i >=0; i--) {
cout << numbers1[i] << endl;
}
}
and change your main to:
int main() {
int *arr1 = readNumbers();
reverseArray(arr1,6);
return 0;
}
Now, if you actually want to return this array, you would need to create a new array which holds the reverse numbers and then return that. An example of a function that does that is:
int* reverseArray(int *numbers1,int length) {
int j = 0;
int *numbers2 = new int[length];
for (int i = length-1; i >=0; i--) {
numbers2[j] = numbers1[i];
j++;
}
return numbers2;
}
There are probably better ways to do this, but this is just one solution. Regardless, you should always be careful when allocating memory yourself.

Run-Time Check Failure #2 - Stack around the variable 'sortObject' was corrupted. how to fix?

I was trying to store numbers in an array. The first half of the array are numbers that are ascending 1,2,3,4,5 etc and the second half of the array are random numbers. When i run the program it produces the output I wanted but gives me the error please help
#include <iostream>
#include <cstdlib>
using namespace std;
class sorting {
private:
int size, elements;
int arr[NULL];
public:
void sort(){
cout << "Enter number of desired elements" << ">"; cin >> elements;
arr[elements];
half();
}
void half() {
for (int i = 0; i < elements/2; i++) {
arr[i] = i + 1;
}
for (int i = elements / 2; i < elements; i++) {
arr[i] = rand();
}
cout << "This is the elements of the array";
for (int i = 0; i < elements; i++) {
cout << arr[i] << " ";
}
}
};
int main()
{
sorting sortObject;
sortObject.sort();
return 0;
}
As i could see you want the array size to change during run time depending on the input, we need to dynamically allocate a array.so take a integer pointer as a field instead of static array.
then inside the sort function after reading the input, dynamically allocate the memory to pointer.(actually its better if we do it in a constructor).
int *arr;
arr=(int *)malloc(elements*sizeof(int));

Is this the correct way to allocate and delete dynamic memory in C++?

I have an assignment for class, in which I need to create 3 functions to test with constant arguments. I am also supposed to create and delete dynamic memory. I have attached the exact directions from the assignment, just in case, as well as my code.
I apologize if the code is messy. I am a beginning programmer and new to the site, so I'm not exactly sure how to format everything perfectly.
Directions from assignment:
Write a C++ program that will test three functions described below that use pointers and dynamic memory allocation.
Expand: takes an int array and the array's size as parameters. It should create a new array that is twice the size of the argument array. The function should copy the contents of the argument array to the new array, and initialize the unused elements of the new array with -1. The function should return a pointer to the new array.
concatenate: takes two int arrays and the arrays' sizes as parameters (that's 4 parameters). It should create a new array big enough to store both arrays. Then it should copy the contents of the first array to the new array, and then copy the contents of the second array to the new array in the remaining elements, and return a pointer to the new array.
subArray: It takes an int array, a start index and a length as arguments. It creates a new array that is a copy of the elements from the original array starting at the start index, and has length equal to the length argument. For example, subArray(aa,5,4) would return a new array containing only the elements aa[5], aa[6], aa[7], and aa[8].
My code:
#include <iostream>
using namespace std;
int* Expand(int [], int);
int* concatenate(int[], int, int[], int);
int* subArray(int[], int, int);
int main()
{
//Declare variables
const int SIZEAA = 10;
const int SIZEBB = 5;
int aa[SIZEAA] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int bb[SIZEBB] = { 11, 22, 33, 44, 55 };
//Output both original arrays
cout << "aa[10]: ";
for (int i = 0; i < SIZEAA; i++)
cout << aa[i] << " ";
cout << endl;
cout << "bb[5]: ";
for (int i = 0; i < SIZEBB; i++)
cout << bb[i] << " ";
cout << endl;
//Call the Expand function
int* aaExpand = Expand(aa, SIZEAA);
//Output expanded array
cout << "Testing Expand: ";
for (int i = 0; i < 20; i++)
cout << aaExpand[i] << " ";
//Release dynamic memory
delete[] aaExpand;
aaExpand = nullptr;
cout << endl;
//Call the concatenate function
int* concatenateArray = concatenate(aa, SIZEAA, bb, SIZEBB);
//Output concatenated array
cout << "Testing concatenate: ";
for (int i = 0; i < (SIZEAA + SIZEBB); i++)
cout << concatenateArray[i] << " ";
//Release dynamic memory
delete[] concatenateArray;
concatenateArray = nullptr;
cout << endl;
//Call subArray function
int* arraySub = subArray(aa, 5, 4);
//Output the sub array
cout << "Testing subArray: ";
for (int i = 0; i < 4; i++)
cout << arraySub[i] << " ";
//Release dynamic memory
delete[] arraySub;
arraySub = nullptr;
cout << endl;
}
int* Expand(int aa[], int size) /*This function takes in an array and
the size as parameters, creates a new array of double the size, and copies
the old array into it.It then adds -1 into all new spaces created.
It returns a pointer to the new array*/
{
//Declare new array
int* aaNew;
int newSize = size * 2;
aaNew = new int[newSize];
//Copy old array into new array
for (int i = 0; i < newSize; i++)
{
if (i >= 0 && i < size) //Check to see if it needs to copy an old value in or put -1 into the array
aaNew[i] = aa[i];
else
aaNew[i] = -1;
}
return aaNew;
}
int * concatenate(int aa[], int sizeAA, int bb[], int sizeBB) /*This
function takes in two different arrays, creates a new array, then copies
both arrays into the new array.It returns a pointer to the new array*/
{
//Create new array size
int newSize = (sizeAA + sizeBB);
//Create new array
int* concatArray;
concatArray = new int[newSize];
//Add elements of first and second array into new array
for (int i = 0; i < newSize; i++)
{
if (i >= 0 && i < sizeAA) //Check to see if a value from the first or second array is supposed to be added
concatArray[i] = aa[i];
else
concatArray[i] = bb[i - sizeAA];
}
return concatArray;
}
int * subArray(int a[], int start, int length) /* This function takes in
an array, a start value, and a length value. It creates a new array and
copies the values of the original array starting at the passed start value
and continues until the new array is the length of the passed length value.
It returns a pointer to the new array*/
{
//Create new array size
int subSize = length;
//Create a new array
int* sub;
sub = new int[subSize];
//Add elements of original array starting at the passed start value into new
array until the new array is the length specified by the argument
for (int i = 0; i < subSize; i++)
{
sub[i] = a[start];
start += 1;
}
return sub;
}
Your set up is very good. Glad to see you're getting the hang of it. Your functions could use some optimization, however. Before we begin, Id 'd like to note that C++ has a std::vector class which dynamically allocates memory as needed and supplies many powerful mod functions. I'd recommend checking that out as it would take your program to the next level.
To begin, Your Expand()function is pretty well set up. Just some minor modifications: to clean up your code,
int* aaNew;
int newSize = size * 2;
aaNew = new int[newSize];
can simply become:
int newSize = size * 2;
int *aaNew = new int[newSize];
and within your for loop, there is no need to check the complete range of i, only its upper bound:
if (i >= 0 && i < size)
can become:
if (i < size)
This will have the same result as your if-statement but is more elegant since i will never be less than 0.
Moving on, your concatenate() function could become a lot simpler. While what you are doing is technically correct and works, your concatenate() function could simplify to:
int * concatenate(int aa[], int sizeAA, int bb[], int sizeBB) {
int * result = new int[sizeAA + sizeBB];
copy(aa, aa + sizeAA, result);
copy(bb, bb + sizeBB, result + sizeAA);
return result;
}
Furthermore, in your subArray() function, you can reduce:
//Create new array size
int subSize = length;
//Create a new array
int* sub;
sub = new int[subSize];
to:
//Create new array size
int subSize = length;
int *sub = new int[subSize];
Lastly, your main function could use an overhaul. Consider adding a writeArray() function since you are repeating that task often:
string writeArray(int ar[], int arLength) {
string ret = "";
for (int i = 0; i < arLength; i++)
ret += " " + to_string(i);
return ret + "\n";
}
That way your main() can become:
int main() {
//Declare variables
const int SIZEAA = 10, SIZEBB = 5;
int aa[SIZEAA] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int bb[SIZEBB] = { 11, 22, 33, 44, 55 };
//Output both original arrays
cout << "aa[10]: " << writeArray(aa, SIZEAA);
cout << "bb[5]: " << writeArray(bb, SIZEBB);
//Call the Expand function
int *aaExpand = Expand(aa, SIZEAA);
cout << "Testing Expand: " << writeArray(aaExpand, SIZEAA * 2);
//Call the concatenate function
int *concatenateArray = concatenate(aa, SIZEAA, bb, SIZEBB);
cout << "Testing concatenate: " << writeArray(concatenateArray,
(SIZEAA + SIZEBB));
//Call subArray function
int *arraySub = subArray(aa, 5, 4);
cout << "Testing subArray: " << writeArray(arraySub, 4);
//Output the sub array
//Release dynamic memory
delete[] aaExpand;
delete[] concatenateArray;
delete[] arraySub;
aaExpand = nullptr;
concatenateArray = nullptr;
arraySub = nullptr;
}
The rest of your program looks decent. Keep up the good work!
int* Expand(int elements[], int size)
{
int* new_elements = new int[2 * size];
for (int i = 0; i < size; i++)
{
new_elements[i] = elements[i];
new_elements[i + size] = -1;
}
return new_elements;
}
int* concatenate(int first[], int firstSize, int second[], int secondSize)
{
int* elements = new int[firstSize + secondSize];
for (int i = 0; i < firstSize; i++)
{
elements[i] = first[i];
}
for (int j = 0; i < secondSize; j++)
{
elements[firstSize + j] = second[j];
}
return elements;
}
int* subArray(int elements[], int offset, int size)
{
int* new_elements = new int[size];
for (int i = 0; i < size; i++)
{
new_elements[i] = elements[offset + i];
}
return new_elements;
}

Incorrect Variable output with Vector Class C++

My output for the call to the temporary array size wont correctly output. It resizes as according, but I can't get the MAX to display the new value of the new array. My error is within the Resize function within the class.
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#include <ctime>
using namespace std;
class VectorClass {
private:
int * Vector;//This will be our resizeable array
int Size; //Keep track of vector current size
int MAX=10;
int growth = 5;
int num;
int Resize(int growth, int MAX);
public:
VectorClass(int growth, int Size);
~VectorClass();
int AddItem(int num);
void RemoveItem();
void Print(void);
};
VectorClass::VectorClass(int growth, int Size)
{
Size = 10;
growth = 5;
Vector = new int[Size];
}
VectorClass::~VectorClass()
{
cout << "Destructor was called." << endl;
}
//Will insert num into the vector at the current open position
int VectorClass::AddItem(int num)
{
Vector[Size] = num;
Size++; //Indicate that there isnt as much free space
if (Size == MAX)
{
Resize(Size, MAX);
}
Print();
return num;
}
//Get rid of the most recently added item
void VectorClass::RemoveItem()
{
Size--; //Tricks the vector into one fewer elements in it it currently does
Print();
}
int VectorClass::Resize(int growth, int MAX)
{
cout << "Array is full! Resizing the Array!" << endl;
//Step 1: make a copy
int * temp = new int[MAX]; //Make a new array, same size as exiting array
//loop that copies the original into the copy
for (int i = 0; i<MAX; i++)
{
temp[i] = Vector[i];
}
//Step 2: Delete the original
delete[] Vector; //Deletes all elements in the array Vector from the Heap
//Step 3: Make a bigger vector
Vector = new int[MAX + growth];
//Step 4: Reverse the copy and record the size change
for (int i = 0; i<MAX; i++)
{
Vector[i] = temp[i];
}
MAX = MAX + growth;
//Step 5: Delete the copy
delete[] temp;
cout << "Resize was called.\n" << endl;
return MAX;
}
void VectorClass::Print()
{
cout << "*******************************************************" << endl;
for (int i = 0; i< Size; i++)
{
cout << Vector[i] << endl;
}
cout << "Size = " << Size << "\tMAX = " << MAX << "\t Growth = " << growth << endl << endl;
cout << "*******************************************************" << endl;
}
int main(void)
{
VectorClass V(5,10);
for (int i = 0; i <= 4; i++)
{
int x = rand();
V.AddItem(x);
}
//Print the Vector #1
V.Print();
//Delete 2 Items
V.RemoveItem();
V.RemoveItem();
//Add 9 random Numbers
for (int i = 0; i <= 8; i++)
{
int x = rand();
V.AddItem(x);
}
//Print the Vector
V.Print();
system("pause");
return 0;
}
Several things are wrong with you code. The first one, probably not the one you care about most, is that you never free the memory. You should do it in your destructor, or even better use a std::unique_ptr to handle your memory.
Now, i believe you are yourself confused about your own variables. I see that you possess a variable member named num that you never use. Even worse, you have a parameter in AddItem with the same name. Are you sure it does what you want? The same is true for growth. I would advise you to name your member variable differently, so that you know what they are quickly. I prefixe them with "m_" for example, but you can do as you wish.
You do not need to declare your function parameters inside your class. Only in the function prototype.
Then, in your AddItem function, you use your variable Size to determine where to add the new element, but you initialize your array with it too, which means that not only you do not add your elements at the beginning of your array, you try to write them in memory you do not own!
I could continue for a long time. I am sorry but it only appears to me that you do not know C++ at all. You should go learn the basics again, and maybe start with an easier project to begin your C++ learning.
Good luck :-)

copying elements from one array to another

I am getting a crash error at run time and not sure what exactly to do with the function or how to get the data for it.
FUNCTION DETAILS
Write a function that accepts an int array and size as arguments, then create a new array that is one element bigger than the given. Setting the first element to 0, then copying over what is in the argument array to the new array.
MAIN DETAILS
Use in a program reading int n from input, then read int n from file data name data
passing it to element shifter, then printing it to output (one per line).
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int element_shift(int elmts[], int size) {
int new_size = size + 1;
int shifter[new_size];
int *elmt_sft;
shifter[0] = 0;
for (int i = 1; i >= new_size; i++) {
shifter[i + 1] = elmts[i];
}
return *elmt_sft;
}
int main() {
fstream infile;
infile.open("D:\\data.txt");
int n, x;
infile >> x;
cout << "size of array: ";
cin >> n;
const int ARRAY_SIZE = n + x;
int elements[ARRAY_SIZE];
element_shift(elements, ARRAY_SIZE);
system("PAUSE");
return EXIT_SUCCESS;
}
First of all ARRAY_SIZE declared in the main function is not a constant variable but defined at run-time depending on user inputs. This means that the array elements should be created dynamically. On the other hand you read some x variable which is only used to define the size of the array and didn't initialized the array at all. I guess that the problem statement is to read the size of the array from the input, then the data of the array from the file.
There are also lot of mistakes in element_shift function.
Your code should look like something similar to this:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
void element_shift(int* elmts, int size)
{
int new_size = size + 1;
int* shifter = new int[new_size];
shifter[0] = 0;
for(int i = 0; i < size; ++i)
{
shifter[i + 1] = elmts[i];
}
delete [] elmts;
elmts = shifter;
}
int main()
{
fstream infile;
infile.open("D:\\data.txt");
int n;
cout << "size of array: ";
cin >> n;
int* elements = new int[n];
for (int i = 0; i < n; ++i) {
infile >> elements[i];
}
element_shift(elements, n);
for (int i = 0; i < n; ++i) {
std::cout << elements[i] << std::endl;
}
return EXIT_SUCCESS;
}
First off, you spend alot of time creating the shifted array but don't return it back.
int element_shift(int elmts[], int size) {
int new_size = size + 1;
int shifter[new_size];
int *elmt_sft;
shifter[0] = 0;
for (int i = 1; i >= new_size; i++) {
shifter[i + 1] = elmts[i];
}
return *elmt_sft;
}
The elmt_sft pointer is never assigned. You are trying to access memory that is not there by using *elmt_sft. This may be causing your error. Also this function has no way of returning the new array shifter because that variable is locally declared and will disappear once the function exits. If you want to create something new in the function and still have it in memory once the function exits, I recommend creating the array dynamically and returning a pointer to it.
This is untested but should start you in the right direction. It will return a separate dynamically allocated array that will not override your other one.
int* element_shift(int elmts[], int size) {
int *result_array = new int[size + 1]; //dynamically create new array MAKE SURE TO DELETE
result_array[0] = 0; //set 0 index to 0
for (int i = 1; i < size + 1; i++)//start at 1 of the result and put value in
{
result_array[i] = elmts[i - 1];
}
return result_array; //returning pointer
}