Using dynamic memory allocation to add elements into an array - c++

I'm supposed to write some code to ask the user to enter an array (1.3 4 5.2 16.3 9.99 7.21 4.5 7.43 11.21 12.5).
After that, I create a new array with a bigger size (double the size), copy all the elements from the old array to the new one, then ask the user to continue to enter 5 more elements to the new array: 1.5 4.5 9.5 16.5 7.5 11.5, and then print out the final array (15 elements).
Here is my code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
double* read_data(int& size)
{
int max = 10;
double* a = new double[max]; // allocated on heap
size = 0;
cout << "Enter the array: " << endl;
while (cin >> a[size])
{
size++;
}
if (size >= max)
{
double* temp = new double[max * 2];
for (int i = 0; i < size; i++)
{
temp[i] = a[i];
}
delete[] a;
a = temp;
max = max * 2;
}
return a;
}
int main ()
{
int input1, input2, input3, input4, input5;
int size = 0;
double* arr = read_data(size);
cout << "Please enter 5 more elements: " << endl;
cin >> input1 >> input2 >> input3 >> input4 >> input5;
arr[10] = input1;
arr[11] = input2;
arr[12] = input3;
arr[13] = input4;
arr[14] = input5;
cout << "The final array is: " << endl;
for (int i = 0; i < 15; i++)
{
cout << arr[i];
}
system("pause");
return 0;
}
It doesn't let me enter 5 more elements and I don't know why.
Please help.

You are waiting for the input stream to enter a "false" state, that happens most visibly when there is an end of file character inputted to the stream. So while inputting code to the terminal if you type in a -d you should see the code move onto the segment after the while loop.
To get away from this problem you will have to specify a limit to the array you are getting from the user so as to not overwrite memory out of bounds.
So change your code to this
#include <iostream>
#include <string>
using namespace std;
double* read_data(int& size)
{
int max = 10;
double* a = new double[max]; // allocated on heap
size = 0;
cout << "Enter the array: " << endl;
while (size < 10 && cin >> a[size])
{
size++;
}
if (size >= max)
{
double* temp = new double[max * 2];
for (int i = 0; i < size; i++)
{
temp[i] = a[i];
}
delete[] a;
a = temp;
max = max * 2;
}
return a;
}
int main ()
{
int input1, input2, input3, input4, input5;
int size = 0;
double* arr = read_data(size);
cout << "Please enter 5 more elements: " << endl;
cin >> input1 >> input2 >> input3 >> input4 >> input5;
arr[10] = input1;
arr[11] = input2;
arr[12] = input3;
arr[13] = input4;
arr[14] = input5;
cout << "The final array is: " << endl;
for (int i = 0; i < 15; i++)
{
cout << arr[i] << ' ';
} cout << endl;
system("pause");
return 0;
}
Notice how I added in the check for the size variable before the "cin" statement, this is referred to as short circuiting (https://en.wikipedia.org/wiki/Short-circuit_evaluation). I do not consider this good style myself but I have included it here to show you how input statements are used in while loops and can cause bad behavior if you don't use it properly.
Also I added in a cout << endl; to flush the stream buffer so that the output does go to the screen before the pause
I just read what you said in the comments and I suggest the following code for the purpose to quit when a 'q' to exit.
#include <iostream>
#include <string>
using namespace std;
double* read_data(int& size)
{
int max = 10;
double* a = new double[max]; // allocated on heap
size = 0;
cout << "Enter the array: " << endl;
char character;
while (size < 10 && cin >> character)
{
if (character == 'q') break;
a[size] = character - '0';
size++;
}
if (size >= max)
{
double* temp = new double[max * 2];
for (int i = 0; i < size; i++)
{
temp[i] = a[i];
}
delete[] a;
a = temp;
max = max * 2;
}
return a;
}
int main ()
{
int size = 0;
double* arr = read_data(size);
cout << "Please enter 5 more elements: " << endl;
for (int i = size; i < size + 5; ++i) {
cin >> arr[i];
}
// add 5 to the size
size += 5;
cout << "The final array is: " << endl;
for (int i = 0; i < size; i++)
{
cout << arr[i] << ' ';
} cout << endl;
system("pause");
return 0;
}

Related

How to store each user input into array?

I used a do while loop to ask user to enter integer as long as its not 0 or it will exit the program. I'm stuck on how to store every user input into the dynamically allocated array.
#include <iostream>
using namespace std;
int main() {
int *A;
A= new int();
int n;
do{
cout<<"Enter integer: "<<endl;
cin>>n;
cout<< *A + n << endl;
}while(n!=0);
return 0;
}
You are allocating a single int, not an array of ints.
Also, even if you were allocating an array, a statement like *A + n does not add n to the array. It dereferences A to access the value of the 1st int in the array, and then adds n to that value.
Try something more like this instead:
#include <iostream>
using namespace std;
int main() {
int *A = nullptr;
int count = 0, n;
do{
cout << "Enter integer: " << endl;
cin >> n;
if (n == 0) break;
int *newA = new int[count+1];
for(int i = 0; i < count; ++i) newA[i] = A[i];
newA[count] = n;
delete[] A;
A = newA;
++count;
cout << A[count-1] << endl;
}
while (true);
delete[] A;
return 0;
}
Alternatively, try to avoid reallocating the array on every input, eg:
#include <iostream>
using namespace std;
int main() {
int *A = new int[5];
int count = 0, cap = 5, n;
do{
cout << "Enter integer: " << endl;
cin >> n;
if (n == 0) break;
if (count == cap)
{
int newCap = cap * 1.5;
int *newA = new int[newCap];
for(int i = 0; i < count; ++i) newA[i] = A[i];
delete[] A;
A = newA;
cap = newCap;
}
A[count] = n;
++count;
cout << A[count-1] << endl;
}
while (true);
delete[] A;
return 0;
}
That being said, a better option is to use a std::vector, which will handle the dynamic memory for you, eg:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> A;
int n;
do{
cout << "Enter integer: " << endl;
cin >> n;
if (n == 0) break;
A.push_back(n);
cout << A.back() << endl;
}
while (true);
return 0;
}

Pointers/References in C++ Project

I've been learning C++ for only a couple of months. We had a project that was due about pointers/reference. This is my code below that I submitted. However, My teacher said I didn't include pointers/references in my code. I was certain that I did on line 31-42. I'm having trouble understanding pointers. Please give feedback on what I should do differently.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
//Opening File
ifstream cafefile;
cafefile.open("cafeteria.txt");
//Check for errors
if (!cafefile)
{
cout << "cafeteria.txt did not open properly" << endl;
exit(9999);
}
//String & char
string choice;
string array[4][3];
char out;
//Pointers to the food
string food[] { "Cheese Pizza", "Hamburger", "Fish Sticks", "Mystery Meat" };
string *foodptr {food};
//Set yes & no to 4 array
int yes[4]{ 0 };
int no[4]{ 0 };
//pointer for integer Yes / NO
int* yesptr{ yes };
int* noptr{ no };
//Counters of Likes & Dislikes set = 0
int like = {0};
int dislike = {0};
for (int i = 0; i < 4; i++)
{
//Reopen the file
ifstream file("cafeteria.txt");
while (getline(file, choice))
{
istringstream pick(choice); //istringstream is input stream class, which operates on string
getline(pick, choice, '\t');
if (foodptr[i] == choice)
{
pick >> choice;
if (choice == "Y")
like++; //increment
else if (choice == "N")
dislike++; //increment
}
}
//Setting the yes = like
yesptr[i] = like;
noptr[i] = dislike;
//Set to 0
like = 0;
dislike = 0;
}
for (int m = 0; m < 4; m++)
{
array[m][0] = foodptr[m];
}
for (int j = 0; j < 4; j++)
{
array[j][1] = to_string(yesptr[j]);
}
for (int i = 0; i < 4; i++)
{
array[i][2] = to_string(noptr[i]);
}
//Display of the Program
cout << "School Cafeteria Survey!" << endl;
cout << endl;
cout << "Food Item" << "\t" << "Like" << "\t" << "Dislike" << endl; //Gives the tab space Horizontally in your output
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
cout << array[i][j] << "\t";
}
cout << endl;
}
//Background color, making it unique
system("color 6");
//Exit the Prgram
cout << endl;
cout << "Please enter 'E' to exit!";
cin >> out;
if (out == 'e' || out == 'E')
{
exit(0);
}
system("pause"); //pause the program
return 0;
}
Please provide solutions on what I should fix.
It would be better if you create your arrays dynamically i.e. make the 2D array dynamically using pointers
string **array;
array = new int *[4];
for(int i=0; i<4; i++){
array[i] = new int[3];
}
Other than this, your teacher must have wanted your to access these array not using indexing, but rather by using pointers and references. This means that you shouldn't access arrays using yesptr[i] but rather by using *(yesptr + i).
So for e.g. if you are in a loop do the following
for (int m = 0; m < 4; m++)
{
*(*(array+m)+0) = *(foodptr+m);
}

Run Time Check Error # 2

#include <string.h>
#include "BubbleSort.h"
void BubbleSort(char Str[])
{
int i;
int NumElements;
bool Sorted;
char Temp;
NumElements = strlen(Str);
do {
Sorted = true;
NumElements--;
for (i = 0; i < NumElements; i++)
if (Str[i] > Str[i + 1])
{
Temp = Str[i];
Str[i] = Str[i + 1];
Str[i + 1] = Temp;
Sorted = false;
}
} while (!Sorted);
}
/////////////////////////////////////////////
#include <iostream>
#include "Bubblesort.h"
using namespace std;
void main() {
int Num;
char Array[20];
cout << "How many numbers would you like to enter?" << endl;
cin >> Num;
cout << "Enter your numbers:" << endl;
for (int i = 0; i < Num; i++)
{
cin >> Array[i];
}
cout << "Here are the numbers you entered:" << endl;
for (int i = 0; i < Num; i++)
{
cout << Array[i] << " ";
}
cout << endl << endl;
BubbleSort (Array);
cout << "Here are your sorted numbers:" << endl;
for (int i = 0; i < Num; i++)
{
cout << Array[i] << " ";
}
cout << endl;
}
////////////////////////////////////////////////////////
#ifndef BUBBLE_SORT_H
#define BUBBLE_SORT_H
void BubbleSort(char[]);
#endif
I get a Run Time Error stating that Num was corrupted. Can anyone help pinpoint the problem in my code?
Thanks
char Array[20] while the Num you input is larger than 20, it will corrupt.
Better use vector and push_back
One mistake is that you're calling strlen on a char array that is not guaranteed to be NULL terminated:
NumElements = strlen(Str);
Thus NumElements has an undetermined value.
You need to either:
1) pass the actual number of characters that are to be sorted as a parameter, along with the array and getting rid of the call to strlen:
BubbleSort(Array, Num);
//...
void BubbleSort(char Str[], int NumElements)
or
2) Make sure the char array you're passing is null terminated

Problems in managing Memory-leaks C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm not getting any errors or something like this, but the problem is that no matter what I do, I can't get rid of those memory-leaks. The only solution that i found that helps me is to add delete[] vector1 after every method but I'm not allowed to modify that part of the code.
In the code you can see the comments and the areas where I can add new instructions. Is there any solution to my problem?
THIS IS THE CODE:
#include<iostream>
using namespace std;
/*YOU CAN'T ADD NEW METHODS*/
/*YOU CAN ONLY MODIFY THE BODY OF THE METHODS*/
//read array from the console - number of elements and the elements
int * readVectorVersion1(int * noElements) {
int *vector1;
vector1 = new int[*noElements + 1];
for (int i = 0; i < *noElements; i++)
{
cout << endl << "Vector1[" << i + 1 << "]=";
cin >> vector1[i];
}
return vector1;
}
//read array from the console - number of elements and the elements
void readVectorVersion2(int ** vector, int* noElements) {
*vector = new int[*noElements + 1];
for (int i = 0; i < *noElements; i++)
{
cout << endl << "Vector1[" << i + 1 << "]=";
cin >> (*vector)[i];
}
}
//read array from the console - number of elements and the elements
void readVectorVersion3(int *& vector, int& noElements) {
vector = new int[noElements + 1];
for (int i = 0; i < noElements; i++)
{
cout << endl << "Vector1[" << i + 1 << "]=";
cin >> vector[i];
}
}
//read array from the console - number of elements and the elements
int * readVectorVersion4(int& noElements) {
int *vector1;
vector1 = new int[noElements + 1];
for (int i = 0; i < noElements; i++)
{
cout << endl << "Vector1[" << i + 1 << "]=";
cin >> vector1[i];
}
return vector1;
}
//read static array from the console - number of elements and the elements
void readStaticVector(int vector[], int * noElements) {
for (int i = 0; i < *noElements; i++)
{
cout << endl << "Vector1[" << i + 1 << "]=";
cin >> vector[i];
}
}
//print the elements of the array
void afisareVector(int* vector, int noElements) {
cout << endl << "Vector:" << endl;
for (int i = 0; i < noElements; i++)
cout << vector[i] << " ";
}
//read a name from the console
char* citesteNume() {
char temp[200];
char * nume;
cout << endl << "Your name:";
cin >> temp;
nume = new char[strlen(temp) + 1];
strcpy(nume, temp);
return nume;
}
//read a name from the console
void citesteNume(char* nume) {
cout << endl << "Your name:";
cin >> nume;
}
//METHODS THAT ADDS AN ELEMENT (THAT IS GIVEN) TO AN EXISTING ARRAY
//FIRST
void adaugaElementNou(int** vector, int* noElemente, int elementNou) {
(*vector) = new int[*noElemente + 2];
for (int i = 0; i < *noElemente; i++)
(*vector)[i] = i;
(*vector)[*noElemente] = elementNou;
}
//SECOND
int * adaugaElementNou(int& noElemente, int elementNou) {
int *vector;
vector = new int[noElemente + 2];
for (int i = 0; i < noElemente; i++)
vector[i] = i;
vector[noElemente] = elementNou;
return vector;
}
//THIRD
int * adaugaElementNou(int* noElemente, int elementNou) {
int *vector;
vector = new int[(*noElemente) + 2];
for (int i = 0; i < *noElemente; i++)
vector[i] = i;
vector[*noElemente] = elementNou;
return vector;
}
//THE PROGRAM MUST RUN AND NOT GENERATE ANY ERRORS OR MEMORY-LEAKS
void main() {
//YOU CAN'T ADD NEW VARIABLES
int * vector1;
int vector2[50];
int nrElementeVector1=3;
int nrElementeVector2=3;
//YOU CAN ADD NEW INSTRUCTIONS
// ...
vector1 = new int[nrElementeVector1 + 1];
for (int i = 0; i < nrElementeVector1; i++)
vector1[i] = i;
for (int i = 0; i < nrElementeVector2; i++)
vector2[i] = i;
//YOU CAN'T MODIFY THE FOLLOWING CODE
afisareVector(vector1, nrElementeVector1);
afisareVector(vector2, nrElementeVector2);
//delete[]vector1; /*This instruction is added by me but i`m not allowed to modify this area of the code*/
vector1 = readVectorVersion1(&nrElementeVector1);
afisareVector(vector1, nrElementeVector1);
//delete[]vector1;
readVectorVersion2(&vector1, &nrElementeVector1);
afisareVector(vector1, nrElementeVector1);
//delete[]vector1;
readVectorVersion3(vector1, nrElementeVector1);
afisareVector(vector1, nrElementeVector1);
//delete[]vector1;
vector1 = readVectorVersion4(nrElementeVector1);
afisareVector(vector1, nrElementeVector1);
//delete[]vector1;
readStaticVector(vector2, &nrElementeVector2);
afisareVector(vector2, nrElementeVector2);
char* string1;
char string2[50];
string1 = citesteNume();
cout << endl << "Hello " << string1;
//delete[]string1; /*THIS IS NOT ALLOWED HERE*/
citesteNume(string2);
cout << endl << "Hello " << string2;
vector1 = adaugaElementNou(nrElementeVector1, 99);
afisareVector(vector1, nrElementeVector1+1);
//delete[]vector1;
adaugaElementNou(&vector1, &nrElementeVector1, 55);
afisareVector(vector1, nrElementeVector1+1);
//delete[]vector1;
vector1 = adaugaElementNou(&nrElementeVector1, 77);
afisareVector(vector1, nrElementeVector1+1);
//delete[]vector1;
//YOU CAN ADD NEW INSTRUCTIONS HERE
// ...
delete[] vector1; //I`ve tried to use delete here because I didn`t knew what else i should do, but I know that it makes no sense(and it`s not working);
delete[] string1;
//THE FOLLOWING CODE CHECKS IF THERE ARE ANY MEMORYLEAKS
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
_CrtDumpMemoryLeaks();
//YOU CAN'T MODIFY THE FOLLOWING CODE
vector1 = NULL;
string1 = NULL;
cout << endl << "In this moment there are no memory-leaks!";
}
For string1 it's simple, you can just:
delete[] string1;
And this is what I think you are supposed to do deal with vector1:
void afisareVector(int* vector, int noElements) {
cout << endl << "Vector:" << endl;
for (int i = 0; i < noElements; i++)
cout << vector[i] << " ";
// A very dirty hack, PLEASE **NEVER** USE IT.
static int callIndex = 0;
if(callIndex != 1 && callIndex != 6)
delete[] vector;
++callIndex;
}
valgrind summary:
==20937== HEAP SUMMARY:
==20937== in use at exit: 0 bytes in 0 blocks
==20937== total heap usage: 9 allocs, 9 frees, 144 bytes allocated
==20937==
==20937== All heap blocks were freed -- no leaks are possible
==20937==
==20937== For counts of detected and suppressed errors, rerun with: -v
==20937== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Edit: I changed my mind. The example above is what you can do and this is what you are supposed to do:
Note #1: this hack feels even dirtier to me.
Note #2: In order to compile it, I had to remove all Microsoft-specific stuff and perform a leak checking with the valgrind.
#include<iostream>
#include<cstring>
using namespace std;
/*YOU CAN'T ADD NEW METHODS*/
/*YOU CAN ONLY MODIFY THE BODY OF THE METHODS*/
//read array from the console - number of elements and the elements
int * readVectorVersion1(int * noElements) {
static int vector1[50];
for (int i = 0; i < *noElements; i++)
{
cout << endl << "Vector1[" << i + 1 << "]=";
cin >> vector1[i];
}
return vector1;
}
//read array from the console - number of elements and the elements
void readVectorVersion2(int ** vector1, int* noElements) {
static int vector [50];
for (int i = 0; i < *noElements; i++)
{
cout << endl << "Vector1[" << i + 1 << "]=";
cin >> vector[i];
}
*vector1 = vector;
}
//read array from the console - number of elements and the elements
void readVectorVersion3(int *& vector1, int& noElements) {
static int vector [50];
for (int i = 0; i < noElements; i++)
{
cout << endl << "Vector1[" << i + 1 << "]=";
cin >> vector[i];
}
vector1 = vector;
}
//read array from the console - number of elements and the elements
int * readVectorVersion4(int& noElements) {
static int vector1 [50];
for (int i = 0; i < noElements; i++)
{
cout << endl << "Vector1[" << i + 1 << "]=";
cin >> vector1[i];
}
return vector1;
}
//read static array from the console - number of elements and the elements
void readStaticVector(int vector[], int * noElements) {
for (int i = 0; i < *noElements; i++)
{
cout << endl << "Vector1[" << i + 1 << "]=";
cin >> vector[i];
}
}
//print the elements of the array
void afisareVector(int* vector, int noElements) {
cout << endl << "Vector:" << endl;
for (int i = 0; i < noElements; i++)
cout << vector[i] << " ";
}
//read a name from the console
char* citesteNume() {
char temp[200];
char * nume;
cout << endl << "Your name:";
cin >> temp;
nume = new char[strlen(temp) + 1];
strcpy(nume, temp);
return nume;
}
//read a name from the console
void citesteNume(char* nume) {
cout << endl << "Your name:";
cin >> nume;
}
//METHODS THAT ADDS AN ELEMENT (THAT IS GIVEN) TO AN EXISTING ARRAY
//FIRST
void adaugaElementNou(int** vector, int* noElemente, int elementNou) {
static int vector1 [50];
for (int i = 0; i < *noElemente; i++)
vector1[i] = i;
vector1[*noElemente] = elementNou;
*vector = vector1;
}
//SECOND
int * adaugaElementNou(int& noElemente, int elementNou) {
static int vector [50];
for (int i = 0; i < noElemente; i++)
vector[i] = i;
vector[noElemente] = elementNou;
return vector;
}
//THIRD
int * adaugaElementNou(int* noElemente, int elementNou) {
static int vector [50];
for (int i = 0; i < *noElemente; i++)
vector[i] = i;
vector[*noElemente] = elementNou;
return vector;
}
//THE PROGRAM MUST RUN AND NOT GENERATE ANY ERRORS OR MEMORY-LEAKS
int main() {
//YOU CAN'T ADD NEW VARIABLES
int * vector1;
int vector2[50];
int nrElementeVector1=3;
int nrElementeVector2=3;
//YOU CAN ADD NEW INSTRUCTIONS
for (int i = 0; i < nrElementeVector2; i++)
vector2[i] = i;
vector1 = vector2;
//YOU CAN'T MODIFY THE FOLLOWING CODE
afisareVector(vector1, nrElementeVector1);
afisareVector(vector2, nrElementeVector2);
vector1 = readVectorVersion1(&nrElementeVector1);
afisareVector(vector1, nrElementeVector1);
readVectorVersion2(&vector1, &nrElementeVector1);
afisareVector(vector1, nrElementeVector1);
readVectorVersion3(vector1, nrElementeVector1);
afisareVector(vector1, nrElementeVector1);
vector1 = readVectorVersion4(nrElementeVector1);
afisareVector(vector1, nrElementeVector1);
readStaticVector(vector2, &nrElementeVector2);
afisareVector(vector2, nrElementeVector2);
char* string1;
char string2[50];
string1 = citesteNume();
cout << endl << "Hello " << string1;
citesteNume(string2);
cout << endl << "Hello " << string2;
vector1 = adaugaElementNou(nrElementeVector1, 99);
afisareVector(vector1, nrElementeVector1+1);
adaugaElementNou(&vector1, &nrElementeVector1, 55);
afisareVector(vector1, nrElementeVector1+1);
vector1 = adaugaElementNou(&nrElementeVector1, 77);
afisareVector(vector1, nrElementeVector1+1);
//YOU CAN ADD NEW INSTRUCTIONS HERE
// ...
delete[] string1;
//YOU CAN'T MODIFY THE FOLLOWING CODE
vector1 = NULL;
string1 = NULL;
}
valgrind output:
==21224== HEAP SUMMARY:
==21224== in use at exit: 0 bytes in 0 blocks
==21224== total heap usage: 1 allocs, 1 frees, 2 bytes allocated
==21224==
==21224== All heap blocks were freed -- no leaks are possible
==21224==
==21224== For counts of detected and suppressed errors, rerun with: -v
==21224== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Edit: I came up with the 3rd (even dirtier) solution, but I'm too tired of all this hacking to write a complete version. Here is an example:
int * readVectorVersion1(int * noElements) {
static int *vector1 = NULL;
delete[] vector1;
if (noElements < 0)
return NULL;
vector1 = new int[*noElements + 1];
for (int i = 0; i < *noElements; i++)
{
cout << endl << "Vector1[" << i + 1 << "]=";
cin >> vector1[i];
}
return vector1;
}
// ...
int main() {
// ...
// Just before _CrtSetReportMode
nrElementeVector1 = -1;
readVectorVersion1(*nrElementeVector1);
// ..
}
I'd say this task is impossible to accomplish. The line
vector1 = readVectorVersion1(&nrElementeVector1);
is executed when vector1 holds a dynamically allocated resource. Creating an unrecoverable leak at this point. The same goes for the following
readVectorVersion2(&vector1, &nrElementeVector1);
The vector1 pointer is overwritten in the code that you may not modify, so clearly it may not be the only pointer to dynamically allocated memory, or else it will leak and there is nothing you can do to stop that, within the restraints of your assignment.
So, let's explore the possibility of using a static object to hold the pointer. I'll use std::vector for simplicity, but you can use a static pointer to dynamic memory if you want to. In that case you'll need to manage the memory manually.
int * readVectorVersion1(int * noElements) {
static std::vector<int> vector1;
vector1.resize(*noElements);
// initialize the way you want to
return vector1.data();
// return &vector1[0]; // use this if you use older version of c++ than c++11
}
And there you go. The memory will be deallocated when static objects are destroyed. This of course does limit what you can do with the function. You can no longer allocate two separate arrays because subsequent calls will use the same vector. But it's not needed for this assignment, so I guess this is what your instructor is asking for.

how to print an array backwards

The user enteres a number which is put in an array and then the array needs to be orinted backwadrds
int main()
{
int numbers[5];
int x;
for (int i = 0; i<5; i++)
{
cout << "Enter a number: ";
cin >> x;
numbers[x];
}
for (int i = 5; i>0 ; i--)
{
cout << numbers[i];
}
return 0;
}
You're very close. Hope this helps.
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int numbers[5];
/* Get size of array */
int size = sizeof(numbers)/sizeof(int);
int val;
for(int i = 0; i < size; i++) {
cout << "Enter a number: ";
cin >> val;
numbers[i] = val;
}
/* Start index at spot 4 and decrement until k hits 0 */
for(int k = size-1; k >= 0; k--) {
cout << numbers[k] << " ";
}
cout << endl;
return 0;
}
You are very close to your result but you did little mistakes, the following code is the correct solution of the code you have written.
int main()
{
int numbers[5];
int x;
for (int i = 0; i<5; i++)
{
cout << "Enter a number: ";
cin >> numbers[i];
}
for (int i = 4; i>=0; i--)
{
cout << numbers[i];
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
//get size of the array
int arr[1000], n;
cin >> n;
//receive the elements of the array
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
//swap the elements of indexes
//the condition is just at "i*2" be cause if we exceed these value we will start to return the elements to its original places
for (int i = 0; i*2< n; i++)
{
//variable x as a holder for the value of the index
int x = arr[i];
//index arr[n-1-i]: "-1" as the first index start with 0,"-i" to adjust the suitable index which have the value to be swaped
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = x;
}
//loop for printing the new elements
for(int i=0;i<n;i++)
{
cout<<arr[i];
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
//print numbers in an array in reverse order
int myarray[1000];
cout << "enter size: " << endl;
int size;
cin >> size;
cout << "Enter numbers: " << endl;
for (int i = 0; i<size; i++)
{
cin >> myarray[i];
}
for (int i = size - 1; i >=0; i--)
{
cout << myarray[i];
}
return 0;
}
of course you can just delete the cout statements and modify to your liking
this one is more simple
#include<iostream>
using namespace std;
int main ()
{
int a[10], x, i;
cout << "enter the size of array" << endl;
cin >> x;
cout << "enter the element of array" << endl;
for (i = 0; i < x; i++)
{
cin >> a[i];
}
cout << "reverse of array" << endl;
for (i = x - 1; i >= 0; i--)
cout << a[i] << endl;
}
answer in c++. using only one array.
#include<iostream>
using namespace std ;
int main()
{
int array[1000] , count ;
cin >> count ;
for(int i = 0 ; i<count ; i++)
{
cin >> array[i] ;
}
for(int j = count-1 ; j>=0 ; j--)
{
cout << array[j] << endl;
}
return 0 ;
}
#include <iostream>
using namespace std;
int main ()
{
int array[10000];
int N;
cout<< " Enter total numbers ";
cin>>N;
cout << "Enter numbers:"<<endl;
for (int i = 0; i <N; ++i)
{
cin>>array[i];
}
for ( i = N-1; i>=0;i--)
{
cout<<array[i]<<endl;
}
return 0;
}