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.
Related
This question already has answers here:
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 1 year ago.
I was asked to create this function:
int * createAndInput(int & size)
The function initializes an array in the size of
the value size, gets the values from the user as input, and returns the allocated array and the size by ref.
Here is the code I have so far:
int *creatAndInput(int& size)
{
int arr1[***size***];
for (int i = 0; i << size; i++)
{
cout << "enter index " << (i + 1) << endl;
cin >> arr1[i];
}
return (arr1);
}
void main()
{
cout << "enter size number" << endl;
int size2 = 10;
int *size1 = &size2;
cout << *creatAndInput(size2);
}
#include <iostream>
int* createAndInput(int& size)
{
int* ptr = new int[size];
for(int i = 0; i < size; i++){
std::cout << i+1 << ". element: ";
std::cin >> ptr[i];
}
return ptr;
}
int main(){
int *ptr, size;
std::cout << "Size: ";
std::cin >> size;
ptr = createAndInput(size);
for(int i = 0; i < size; i++)
std::cout << i+1 << ". element: "<< ptr[i] << std::endl;
delete[] ptr;
return 0;
}
Having issues with my getPosNums3 function.....all the others work as I need them to. I'm having issues in general understanding pointers, but I am sure that will pass. The aforementioned function spits out the size and address as I need it to, but when I print the newly modified array, it prints out long identical negative integers akin to this: -5476891, -5476891. It'll put out the right amount of integers, which tells me it is a small adjustment that is hanging up my code.....all these functions modify an array down to only its positive values; they just do so via different methods. I appreciate the help
#include <iostream>
using namespace std;
typedef int* IntArrayPtr;
int* getPosNums1(int* arr, int arrSize, int& outPosArrSize);
int* getPosNums2(int* arr, int arrSize, int* outPosArrSizePtr);
void getPosNums3(int* arr, int arrSize, int*& outPosArr, int& outPosArrSize);
void getPosNums4(int* arr, int arrSize, int** outPosArrPtr, int* outPosArrSizePtr);
void printNewArray(int* arr, int arrSize);
void fillArray(int a[], int size);
int main() {
cout << "Fuction 1: " << endl;
int array_size;
cout << "What is the size of the array? ";
cin >> array_size;
IntArrayPtr a;
a = new int[array_size];
fillArray(a, array_size);
int posArraySize;
int* posNums1 = getPosNums1(a, array_size, posArraySize);
cout << "Original array is: ";
printNewArray(a, array_size);
cout << "The new address is " << posNums1 << " and the new size is " << posArraySize << " " << endl;
cout << "New array is: ";
printNewArray(posNums1, posArraySize);
delete[] a;
cout << endl;
cout << "Function 2: " << endl;
int array_size2;
cout << "What is the size of the array? ";
cin >> array_size2;
a = new int[array_size2];
fillArray(a, array_size2);
cout << "Original array is: ";
printNewArray(a, array_size2);
int* posArraySize2 = &array_size2;
int* posNums2 = getPosNums2(a, array_size2, posArraySize2);
cout << "The new address is " << posNums2 << " and the new size is " << *posArraySize2 << " " << endl;
cout << "New array is: ";
printNewArray(posNums2, *posArraySize2);
delete[] a;
cout << endl;
cout << "Function 3: " << endl;
int array_size3;
cout << "What is the size of the array? ";
cin >> array_size3;
a = new int[array_size3];
fillArray(a, array_size3);
cout << "Original array is: ";
printNewArray(a, array_size3);
int* posNums3 = new int[array_size3];
int posArraySize3 = array_size3;
getPosNums3(a, array_size3, posNums3, posArraySize3);
cout << "The new address is " << posNums3 << " and the new size is " << posArraySize3 << endl;
cout << "New array is: ";
printNewArray(posNums3, posArraySize3);
delete[] a;
cout << endl;
cout << "Function 4: " << endl;
int array_size4;
cout << "What is the size of the array? ";
cin >> array_size4;
a = new int[array_size4];
fillArray(a, array_size4);
cout << "Original array is: ";
printNewArray(a, array_size4);
int* posNums4ptr = &array_size4;
int* posNums4 = new int[array_size4];
int** posNums4ptrptr = &posNums4;
getPosNums4(a, array_size4, posNums4ptrptr, posNums4ptr);
cout << "The new address is " << posNums4ptrptr << " and the new size is " << *posNums4ptr << endl;
cout << "New array is: ";
printNewArray(posNums4, *posNums4ptr);
delete[] a;
return 0;
}
int* getPosNums1(int* arr, int arrSize, int& outPosArrSize) {
int* newArray = new int[arrSize];
int counter = 0;
for (int i = 0; i < arrSize; i++) {
if (arr[i] > 0) {
newArray[counter] = arr[i];
counter++;
}
}
outPosArrSize = counter;
return newArray;
}
int* getPosNums2(int* arr, int arrSize, int* outPosArrSizePtr) {
int size = 0, counter = 0;
int newArraySize = 0;
for (int i = 0; i < arrSize; i++) {
if (*(arr + i) > 0) {
newArraySize++;
}
}
int* newArray = new int[newArraySize];
for (int i = 0; i < arrSize; i++) {
if (*(arr + i) > 0) {
newArray[counter] = *(arr + i);
size++;
counter++;
}
}
*outPosArrSizePtr = size;
return newArray;
}
void getPosNums3(int* arr, int arrSize, int*& outPosArr, int& outPosArrSize){
int counter = 0, size = 0;
for (int i = 0; i < arrSize; i++) {
if (*(arr + i) > 0) {
size++;
}
}
int *newArray = new int[size];
for (int i = 0; i < arrSize; i++) {
if (*(arr + i) > 0) {
newArray[counter] = *(arr + i);
counter++;
}
}
delete[] outPosArr;
outPosArr = newArray;
outPosArrSize = size;
delete[] newArray;
newArray = nullptr;
}
void getPosNums4(int* arr, int arrSize, int** outPosArrPtr, int* outPosArrSizePtr){
int size = 0, counter = 0, newArraySize = 0;
for (int i = 0; i < arrSize; i++) {
if (*(arr + i) > 0) {
newArraySize ++;
}
}
int* temp = new int[newArraySize];
for (int i = 0; i < arrSize; i++) {
if (*(arr + i) > 0) {
temp[counter] = arr[i];
size++;
counter++;
}
}
*outPosArrSizePtr = size;
*outPosArrPtr = temp;
}
void printNewArray(int* arr, int arrSize) {
for (int i = 0; i < arrSize; i++)
cout << arr[i] << " ";
cout << endl;
}
void fillArray(int a[], int size) {
cout << "Enter " << size << " integers." << endl;
for (int i = 0; i < size; i++)
cin >> a[i];
}
The code in question is
void getPosNums3(int* arr, int arrSize, int*& outPosArr, int& outPosArrSize){
// [snip] count number of positive entries in arr and call it "size"
int *newArray = new int[size];
// [snip] copy positive entries in arr into newArray
delete[] outPosArr;
outPosArr = newArray;
outPosArrSize = size;
delete[] newArray;
newArray = nullptr;
}
First of all, it's not a good idea for this function to delete[] outPosArr because that presumes that outPosArr is either nullptr or something that was previously allocated with new[]. If it isn't one of those two things then this function has undefined behavior.
Somebody calling a function to copy numbers into an array is not typically going to also want the function to clean up some previous thing that may or may not have been in that array.
But your real problem is that you allocate memory for an array via int *newArray = new int[size], copy stuff in, and then immediately deallocate that memory by calling delete[] newArray. This leaves outPosArr to point to what used to be an array.
Also, assigning nullptr to newArray at the end of the function does nothing, because newArray is going out of scope anyway.
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;
}
I am trying to create a get function in my class to return that will take i, j argument and return the value of what is located at Object(i, j).
So far in my get function it is converting i, j to its equivalent in a 1d array by i * (number of columns) + j, which in my code would equal 5.
Next I want to show what value is at location 5 in my array. However it seems to return the first value of my array, not the location 5 value. Any ideas to where I am going wrong? am I using the pointer in the wrong way? My full program is below:
#include <iostream>
using namespace std;
class MyMatrix{
public:
//default constructor set member variables to null states
MyMatrix();
MyMatrix(int sizeR, int sizeC, double * input_data);
~MyMatrix(); //destructor
//member functions
int get(int i, int j);
private:
int m; //rows
int n; //columns
double * data;
};
int main(){
const int rows = 3;
const int columns = 2;
double * userInput;
cout << "The array is 3*2, or 6 elements." << endl;
userInput = new double[rows*columns];
double temp;
for (int i = 0; i < rows*columns; i++){ //let the user type in the array
cout << "Please enter value" << i << endl;
cin >> temp;
*(userInput + i) = temp;
}
MyMatrix ObjectA(rows, columns, userInput); //creating object with specifications
cout << "The value of ObjectA 2,1 is: " << ObjectA.get(2, 1) << endl;
return 0;
}
MyMatrix::MyMatrix(){
cout << "MyMatrix constructor lets go" << endl;
m = 0;
n = 0;
data = 0;
}
MyMatrix::MyMatrix(int sizeR, int sizeC, double * input_data){
cout << "MyMatrix::MyMatrix(int sizeR, int sizeC, double * input_data) is called." << endl; //Showing the constructor working :)
m = sizeR;
n = sizeC;
data = new double[m*n];
for (int i = 0; i < m*n; i++){
data[i] = *input_data;
}
cout << "The items you have entered are:" << endl; //printing out array showing the array is filled
for (int i = 0; i < m*n; i++){
cout << i << "item is: " << *(input_data + i) << endl;
}
}
int MyMatrix::get(int i, int j){
cout << "getFunction is happening" << endl;
//val should just be K [K = i * N + j]
int val = 0;
val = i * n + j; //n is COLUMNS, m is ROWS derp
cout << "val is equal to: " << val << endl; //so val would be 5
//how do i get it to display what is at location 5 in object A
return data[val]; // shouldnt this return the 5th element in data?
}
MyMatrix::~MyMatrix(){
cout << "MyMatrix::~MyMatrix() is invoked" << endl; //showing DESTRUCTA function is working
delete[] data; //the memory management
}
Use data[i] = input_data[i] instead data[i] = *input_data, and add delete [] userInput to free memory or you will memory leak.
I have a code that goes like this:
void push(char *buffer, char entry, int length)
{
buffer[length] = entry;
}
void main(void)
{
char * buffer = new char;
int length, x;
cout << "How many: ";
cin >> length;
x = length;
buffer = (char*)malloc(length + 1);
for (int i = 0; i < length; i++)
{
char entry;
cout << "Input: ";
cin >> entry;
push(buffer, entry, i);
}
for (int i = length-1; i >= 0; i--)
{
free(&buffer[i]);
cout << "Success in Removing: " << buffer[i] << endl;
}
}
I need to free the last member of array entered one by one. But I keep getting a breakpoint error. How should I do this?
Make this change and try it-
for (int i = length-1; i >= 0; i--)
{
buffer[i]='\0'; // you can't free one memory location in array of memory
cout << "Success in Removing: " << buffer[i] << endl;
}
In this way only you can remove that last member from your array. After removing every thing delete the memory.
I'm sorry but it hurts my eyes...
void push(char *buffer, char entry, int length)
{
buffer[length] = entry;
}
void main(void)
{
char * buffer; // Nothing to do here
int length, x;
cout << "How many: ";
cin >> length;
x = length;
// buffer = (char*)malloc(length);
// Better
buffer = new char[length];
for (int i = 0; i < length; i++)
{
char entry;
cout << "Input: ";
cin >> entry;
push(buffer, entry, i);
}
for (int i = length-1; i >= 0; i--)
{
buffer[i] = '\0'; // I assume this is some sort of char stack displayable as a string...
cout << "Success in Removing: " << buffer[i] << endl;
}
delete[] buffer;
}
If you are doing a char stack you should probably keep track of the last unsued index or better, use a stack.