Can someone explain me why when i back form function i lost my data from tabOfOffsets. I did the same thing twice and program crash only with the second array.
I printed values of this array on the end of function and everything is clear and correct. Maybe i make mistake somewhere with delete?
Below it is the code.
#include<iostream>
#include <algorithm>
using std::cout;
using std::endl;
void changeSizeOfVector(int *tabValue, int *tabOffsets, int &oldSize, int
newSize) {
int temp = std::min(oldSize, newSize);
int *newTabOfValues = new int [newSize] {0};
int *newTabOfOffsets = new int [newSize] {0};
for (int i = 0; i < temp; i++) {
newTabOfValues[i] = tabValue[i];
newTabOfOffsets[i] = tabOffsets[i];
}
delete[] tabValue;
delete[] tabOffsets;
tabValue = new int [newSize] {0};
tabOffsets = new int [newSize] {0};
for (int i = 0; i < newSize; i++) {
tabValue[i] = newTabOfValues[i];
tabOffsets[i] = newTabOfOffsets[i];
std::cout << tabOffsets[i] << tabValue[i] << endl;
}
oldSize = newSize;
delete[] newTabOfValues;
delete[] newTabOfOffsets;
for (int i = 0; i < newSize; i++) {
std::cout << tabOffsets[i] << tabValue[i] << endl;
}
}
int main() {
int SIZE = 10;
int * tabOfOffsets = new int[SIZE];
int * tabOfValues = new int[SIZE];
for (int i = 0; i < SIZE; i++)
{
tabOfValues[i] = i;
tabOfOffsets[i] = i;
cout << tabOfValues[i] << " : " << tabOfOffsets[i] << endl;
}
changeSizeOfVector(tabOfValues, tabOfOffsets, SIZE, 12);
for (int i = 0; i < SIZE; i++) {
cout << tabOfOffsets[i] << " : " << tabOfValues[i] << endl;
}
delete[] tabOfOffsets;
delete[] tabOfValues;
}
This function declaration is wrong:
void changeSizeOfVector(int *tabValue, int *tabOffsets, int &oldSize, int
newSize);
it means you can change the values of tabOffsets but not the pointer itself in order to make it behave correctly you should declare it as follows:
void changeSizeOfVector(int *tabValue, int **tabOffsets, int &oldSize, int
newSize);
This way you can change the pointer itself and assign a newly allocated array to it.
Related
I wrote C++ programme in vs code and When I run it, it ask me to enter the element value but when I enter the second time, it has stopped working. I don't know what the problem is but if you know the please help me to resolve the problem.
#include <iostream>
using namespace std;
class myArray {
public:
int total_size;
int used_size;
int* ptr;
myArray(int tsize, int usize)
{
total_size = tsize;
used_size = usize;
ptr = new int(tsize);
}
myArray() {}
void setvalue()
{
int n;
for (int i = 0; i < used_size; i++) {
cout << "Enter the element" << endl;
cin >> n;
ptr[i] = n;
}
}
void show()
{
for (int i = 0; i < used_size; i++) {
cout << "The element in array" << endl;
cout << ptr[i] << endl;
}
}
};
int main()
{
myArray(10, 2);
myArray a;
a.setvalue();
a.show();
return 0;
}
You used used_size and ptr without initializing them in a.setvalue(); and a.show();.
It seems
myArray(10, 2);
myArray a;
should be
myArray a(10, 2);
Also, as #Yksisarvinen points out,
ptr = new int(tsize);
should be
ptr = new int[tsize];
to allocate an array instead of single int.
I am new to c++ and learning how to declare, use and delete a two dimensional array of std::string.
Because this is a learning exercise I am ignoring the idea of using vectors (for now).
I wrote a program that creates a small two dimensional array, adds data and then deletes the 2d array trying to use best practices along the way.
Can someone suggest improvements? I am most concerned about cleaning up the 2d array after I'm done using it, so I can avoid the possibility of a memory leak.
Thanks in advance.
#include <iostream>
#include <string>
using namespace std;
void DIM(std::string **marray,unsigned int row,unsigned long cols)
{
if (marray[row] != nullptr) {
delete [] marray[row];
marray[row] = nullptr;
}
marray[row] = new std::string[cols];
}
void DIM_DELETE (std::string **marray,unsigned int row)
{
if (*&marray[row] != nullptr) {
delete[] marray[row];
marray[row] = nullptr;
}
}
void DIM_DELETE_ALL (std::string **marray,unsigned int rows)
{
for (int i=(rows-1); i>-1; i--) {
if (marray[i] != nullptr) {
delete[] marray[i];
marray[i] = nullptr;
}
}//next i
//now take care of marray
if (marray != nullptr) {
delete [] marray;
marray = nullptr;
}
}
std::string **create2darray(unsigned int rows,unsigned int cols)
{
//first create the pointer
std::string **my = nullptr; //create pointer , note: no data portion assigned yet
//now assign a data portion to the pointer (could do above in one step)
my = new std::string*[rows];// elements 0 through rows-1 //assigns data section (an array of std::strings)
//now set newly created rows to nullptr
for (unsigned int i = 0; i<rows; i++) {
my[i] = nullptr;
}
//dim each row for cols columns
for (unsigned int i = 0; i<rows; i++) {
DIM(my,i,cols);//dims the strings (creates data portion) my = new std::string*[x];//
}
return my;//returning a std::string **
}
int main()
{
unsigned int rows = 3;//3 rows (0 through 2)
unsigned int cols = 4;//4 columns (0 through 3)
std::string **myarray = create2darray(rows,cols);//2d array (3 rows, 5 cols)
cout << "2d array created" << endl << endl;
myarray[0][0] = "a0"; //row 0, col 0
myarray[1][0] = "b0"; //row 1, col 0
myarray[2][0] = "c0";
myarray[0][1] = "a1";
myarray[0][2] = "a2";
myarray[0][3] = "a3";
myarray[1][1] = "b1";
myarray[1][2] = "b2";
myarray[1][3] = "b3";
myarray[2][1] = "c1";
myarray[2][2] = "c2";
myarray[2][3] = "c3";
cout << "assigned data to rows 0 to 2 and cols 0 to 3" << endl << endl;
for (unsigned int i=0; i<rows; i++) {
cout << i << ",0: " << myarray[i][0] << " " << i << ",1: " << myarray[i][1] << " " << i << ",2: " << myarray[i][2] << " " << i << ",3: " << myarray[i][3] << endl;
}
cout << endl;
cout << "we are done with 2d array, let's delete it" << endl;
//tested dim_delete (seems to work)
/*
DIM_DELETE(myarray,0);//delete [] myarray[0]; myarray[0] = nullptr;
DIM_DELETE(myarray,1);
DIM_DELETE(myarray,2);
//still need to delete myarray
delete [] myarray;
myarray = nullptr;
*/
//delete all rows and delete the std::string that holds the rows
DIM_DELETE_ALL(myarray,rows);
cout << "array deleted, all done" << endl;
//hold cursor so user can see console messages
do {} while(cin.get()!='\n');
return 0;
}
If the second dimension of your array is constant, I think you can be fine using a single new and delete operators. Something like this:
#include <stdio.h>
#include <string>
int ROWS = 3;
const int COLS = 4;
typedef std::string arr4[COLS];
int main()
{
arr4 *a;
a = new arr4[ROWS];
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLS; j++)
a[i][j] = std::to_string(j*ROWS + i);
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
printf("%s ", a[i][j].c_str());
printf("\n");
}
printf("\n");
delete [] a;
}
I need help, to change the size and arr, in the main function to allocate memory dynamically (dynamically allocated)
this program uses looping for integer numbers for the 1st program, while classes and structs are the second program
program_1
#include <iostream>
#include <iterator>
using namespace std;
void display_desc(const int arr[], int size)
{
int copy_arr[size];
copy(arr, arr + size, copy_arr);
int temp;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (copy_arr[i] > copy_arr[j]) {
temp = copy_arr[i];
copy_arr[i] = copy_arr[j];
copy_arr[j] = temp;
}
}
}
for (int i = 0; i < size; i++) {
cout << copy_arr[i] << " ";
}
cout << endl;
}
int main()
{
int size = 5;
int arr[size];
for (int i = 0; i < size; i++) {
arr[i] = i;
}
display_desc(arr, size);
}
and
program_2
Change the variable that is in int main () to use dynamic memory allocation
#include <iostream>
#include <iterator>
#include <windows.h>
using namespace std;
const int SLOT_ROOM = 5;
class Person {
public:
Person()
{
name = "";
}
Person(string names)
{
name = names;
}
void set_name(string names) { name = names; }
string get_name() { return name; }
private:
string name;
};
struct Slot {
bool blank;
Person person;
};
class rental {
public:
Slot used[SLOT_ROOM];
rental()
{
for (int i = 0; i < SLOT_ROOM; i++) {
Person person;
used[i].person = person;
used[i].blank = true;
}
}
int in(const Person person)
{
for (int i = 0; i < SLOT_ROOM; i++) {
if (used[i].blank) {
used[i].blank = false;
used[i].person = person;
cout << "used in position " << i << endl;
return i;
}
}
cout << "the rental is full" << endl;
return -1;
}
bool out(int i)
{
used[i].blank = true;
}
Slot* get_rental_list()
{
return used;
}
void print_person_list()
{
cout << endl
<< "List rental" << endl;
for (int i = 0; i < SLOT_ROOM; i++) {
cout << "Slot rental to " << i << endl;
cout << "Name: " << used[i].person.get_name() << endl;
cout << "Avail: " << used[i].blank << endl
<< endl;
}
}
private:
int SLOT_ROOM = 2;
string time_rental;
};
int main()
{
rental rental;
Person person_1("make");
Person person_2("angel");
rental.in(person_1);
rental.in(person_2);
rental.print_person_list();
rental.out(2);
rental.print_person_list();
rental.in(person_2);
rental.print_person_list();
}
please help, I don't understand about using dynamic memory allocation
I still learn c ++
Change
int arr[size];
to
int* arr = new int[size];
You need to make the same change to int copy_arr[size]; in display_desc.
You also need to delete[] memory once you've finished with it.
delete[] arr;
at the end of main, and delete[] copy_arr; at the end of display_desc.
In the second question it's harder to understand what you want. Why do you want to use dynamic allocation? Your code looks perfectly good as it is. You also don't say which variable it is that you want to use dynamic allocation.
I have to use pointers to copy values of one array to another. The problem is I'm not allowed to use'[ ]' operators, which makes this more difficult for me. Here is my attempt:
#include <iostream>
using namespace std;
void cpyia(int old_array[],int new_array[],int length){
int *p1 = old_array;
int *p2 = new_array;
int *x = p2;
for(int i=0 ; i<length ; i++){
p2 = x;
p2 = p2 + i;
p2 = p1 + i;
}
for(int i=0; i<5; ++i){
cout << p2[i] << endl;
}
}
int main() {
int a[5]={1,2,3,4,5};
int b[5];
cpyia(a, b, 5);
}
An easier way to do it would be to put p2[i] = p1[i] in the loop, but I cant do that. Any help is appreciated.
The standard way of implementing your function is as follow:
for(int i = 0; i < length; ++i)
*new_array++ = *old_array++;
To be a bit more explicit, it's the same as:
void cpyia(int old_array[],int new_array[],int length){
int *p1 = old_array;
int *p2 = new_array;
for(int i=0 ; i<length ; i++){
*(p2+i) = *(p1+i);
// another way: *(p2++) = *(p1++);
}
}
In real code, you would use std::copy before even thinking about rewriting such a simple thing yourself.
Here is a complete example:
#include <iostream>
#include <algorithm>
void cpyia(int old_array[],int new_array[],int length){
std::copy(old_array, old_array + length, new_array);
}
int main() {
int a[5]={1,2,3,4,5};
int b[5];
cpyia(a, b, 5);
// test results:
for (int index = 0; index < 5; ++index)
{
std::cout << a[index] << " <-> " << b[index] << "\n";
}
}
However, your question says that you are "not allowed to use" something, which sounds a lot like a homework assignment. In that case, you could look at possible implementations of std::copy to get an idea of how to do it. Here is one way:
void cpyia(int old_array[],int new_array[],int length){
int* first = old_array;
int* last = old_array + length;
int* d_first = new_array;
while (first != last) {
*d_first++ = *first++;
}
}
#include<iostream>
using namespace std;
int main() {
const int size = 5;
int arr1[size] = { 4,21,43,9,77 };
int arr2[size];
int *ptr_a = arr1;
int *ptr_b = arr2;
for (int i = 0; i < size; i++)
{
*(ptr_b + i) = *(ptr_a + i);
cout << *(ptr_b + i) << " ";
}
}
I keep getting the error in VS 2100 "CRT detected that the application wrote to memory before start of heap buffer"
Can anyone help? My int Main is all the way on the bottom. The error occur when the delete [] command is run on the operator= function
#include "intset.h"
const int MAXINITIALSIZE = 5;
int IntSet::numOfArray = 0;
IntSet::IntSet(int a, int b, int c, int d, int e)
{
numOfArray++;
int tempArray[] = {a, b, c, d, e};
size = determineHighest(tempArray) + 1; //determines largest int
cout << "size is " << size << endl;
arrayPtr = new bool[size]; //creates array of bool
for (int i = 0; i < size; i++) //fill bool array
{
arrayPtr[i]= false; //arrayptr is a bool pointer created in the header
}
for (int i = 0; i < MAXINITIALSIZE; i++)
{
arrayPtr[tempArray[i]]= true;
}
for (int i = 0; i < size; i++)
{
cout << &arrayPtr[i] << endl;
}
}
IntSet::IntSet(const IntSet &intsetObject)
{
numOfArray++;
size = intsetObject.size;
arrayPtr = new bool[size];
for (int i = 0; i < size; i++)
{
if (intsetObject.arrayPtr[i])
arrayPtr[i] = intsetObject.arrayPtr[i];
}
}
IntSet::~IntSet()
{
--numOfArray;
delete [] arrayPtr;
arrayPtr = NULL;
}
int IntSet::determineHighest(int tempArray[])
{
int temp = tempArray[0];
for (int i = 1; i < MAXINITIALSIZE; i++)
{
if (tempArray[i] > temp)
temp = tempArray[i];
else
continue;
}
return temp;
}
IntSet& IntSet::operator=(const IntSet &intsetObject) //ask about IntSet&
{
cout << "inside operator=" << endl;
if (&intsetObject != this)
{
for (int i = 0; i < size; i++)
{
cout << &arrayPtr[i] << endl;
}
delete [] arrayPtr; //HEAP ERROR HERE!
for (int i = 0; i < size; i++)
{
cout << &arrayPtr[i] << endl;
}
size = intsetObject.size
arrayPtr = new bool[size]();
for (int i = 0; i < size; i++)
{
if (intsetObject.arrayPtr[i])
arrayPtr[i] = intsetObject.arrayPtr[i];
}
}
return *this;
}
ostream& operator<<(ostream &output, const IntSet &intsetObject)
{
output << "{ ";
for (int i = 0; i < intsetObject.size; i++)
{
if (intsetObject.arrayPtr[i] == true)
{
output << i << " ";
}
else
continue;
}
output << "}";
return output;
}
//main
#include "intset.h"
int main() {
IntSet object2(9);
IntSet object4(3,6);
object4 = object2;
return 0;
}
This can only happen if arrayPtr is accessed with a negative index. I suspect your defaults for a,b,c,d,e are -1 in the declaration for IntSet::IntSet, so it is writing to arrayPtr[-1] in the set-true loop. Check for tempArray[i] >= 0 there.
Also, you can't print the array after you have deleted it, so you should remove those lines after the delete, although they should be "harmless" in that only garbage will be printed, but who knows - the OS could release the page containing the array and it could segfault your program.
Finally, you should not test if (intsetObject.arrayPtr[i]) in the copy & = operators. Otherwise all "false" elements in the source array become uninitialized in the destination array (new bool[size] does not initialize the array to all false).