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.
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;
}
In visual studio program crashes: error debug assertion failed. What is wrong in my code? There is no syntax errors. Only warning: deletion of array expression,conversion to pointer suplied When i run it with cmd standart compiler it works fine.
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
#define max_size 100
class my_array{
int* arr[max_size];
public:
my_array() {}
my_array(int size) {
if (size <= 0 || size > max_size) {
exit(1);
}
for (int i = 0; i < size; i++) {
arr[i] = new int;
cout << "Enter element [" << i + 1 << "] = ";
cin >> *arr[i];
}
}
~my_array() {
delete[] arr;
}
void operator[](int n) {
cout << endl;
for (int i = 0; i < n; i++) {
cout << "Enter element [" << i << "] = " << *arr[i] << endl;
}
}
};
int main() {
my_array array(6);
array[5];
return 0;
}
You are deleting arr here:
delete[] arr;
while arr has never been allocated by new. In your original program arr is a fixed size array of pointers to int.
You probably want this:
class my_array {
int *arr;
public:
my_array() {}
my_array(int size) {
if (size <= 0 || size > max_size) { // BTW this test isn't really necessary, as we
// can allocate as much memory as available
// anyway much more than just 100
exit(1);
}
arr = new int[size]; // allocate array of size size
for (int i = 0; i < size; i++) {
cout << "Enter element [" << i + 1 << "] = ";
cin >> arr[i];
}
}
~my_array() {
delete[] arr; // delete array allocated previously
}
void operator[](int n) {
cout << endl;
for (int i = 0; i < n; i++) {
cout << "Enter element [" << i << "] = " << arr[i] << endl;
}
}
};
Instead of having a fixed size array of pointers to int, you have a dynamic array of ints.
There is still room for improvement though. For example the my_array() constructor is pointless here, And it's odd to use the [] operator for printing the content, and the text "Enter element [" in the [] operator is also questionable.
I'm trying to write a function delete an element in a C++ array, that is, shift every element one to the left, starting at the index.
The code
#include <iostream>
using namespace std;
const int MAX_SIZE = 50;
void fill_array(char array[], int ¤t_size, const int max_size);
void print_array(const char array[], const int current_size);
int delete_index(char array[], int ¤t_size, int index);
int main () {
char array[MAX_SIZE] = {' '};
int current_size = 0;
fill_array(array, current_size, MAX_SIZE);
int index = 4;
delete_index(array, current_size, index);
cout << "After deleting element at index " << index << " the array is: ";
print_array(array, current_size);
return 0;
}
int delete_index(char array[], int ¤t_size, int index) {
// Check input
if (index > current_size) {
cout << "Index must be between 0 and " << current_size - 1 << endl;
return -1;
}
for (int i = index; i < current_size; i++) {
cout << "array[" << index << "] = " << index << endl;
array[index] = array[index + 1];
}
current_size--;
cout << current_size << endl;
return 0;
}
However, the output I get when inputting "thisisnotworking" and index 4 is:
Please input characters for the array (max of 50) or enter '*' to quit:
onetwothree*
array[4] = 4
array[4] = 4
array[4] = 4
array[4] = 4
array[4] = 4
array[4] = 4
array[4] = 4
10
After deleting element at index 4 the array is: onetoothre
I don't understand it is not increasing the index in the for loop.
I've read similar questions here and elsewhere but couldn't fix the problem still. Any idea why this is?
NOTE: I only want to use arrays (not vectors, etc.).
for (int i = index; i < current_size; i++) {
cout << "array[" << index << "] = " << index << endl;
array[index] = array[index + 1];
}
Your loop counter is i. Inside your loop, you should use i instead of index
Corrected:
for (int i = index; i < current_size; i++) {
cout << "array[" << i << "] = " << array[i] << endl;
array[i] = array[i + 1];
}
Because you use array[index] = array[index + 1] while you need array[i] = array[i + 1]
It's the same here: cout << "array[" << i << "] = " << i << endl;
use pointers to dynamically change the size:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int* ClearElement(int array[], int index, const int& SizeOrig, int& NewSize)
{
array[index] = -1;
NewSize = SizeOrig;
NewSize--;
int* ptrArray = new int[NewSize];
if(!ptrArray)
throw "No more memory!";
for(int i(0), j(0); i < SizeOrig; i++)
{
if(-1 != array[i])
{
ptrArray[j] = array[i];
j++;
}
}
return ptrArray;
}
int main()
{
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int SizeOrig = (sizeof(array) / sizeof(int));
int NewSize = SizeOrig;
int index;
try{
cout << "element index to clear: ";
cin >> index;
cout << endl;
if(index < 0 || index > NewSize)
throw "out of boundary index!";
int* ptrArray = ClearElement(array, index, SizeOrig, NewSize);
for(int i(0); i < NewSize; i++)
cout << ptrArray[i] << ", ";
delete[] ptrArray;
}
catch(char* cp)
{
cout << cp << endl;
exit(1);
}
catch(...)
{
cout << "sorry an error has happened!";
exit(1);
}
cout << endl << endl << endl;
return 0;
}
You can also use std::copy from algorithm
int max = 10;
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int index = 4;
std::copy(array+index+1, array+max, array+index);
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 am trying to implement a simple merge sort algorithm. What I am very confusing is that
I keep getting the following error message right after the "array2" is deleted.
"
free(): invalid next size (fast)
"
Please advise. Thank you very much!
#include <iostream>
#include <limits.h>
using namespace std;
void merge_sort(int*,int,int);
int main(){
//cout << "Max int: " << INT_MAX <<endl;
int n;
cin >> n;
int* array = new int(n+1);
for (int i=1; i<=n; i++)
cin >> array[i];
merge_sort(array,1,n);
cout << "--------------------------------------------" <<endl;
for (int i=1; i<=n; i++)
cout << array[i] <<endl;
}
void merge_sort(int* array,int p,int r){
cout << p << ' ' << r <<endl;
if (p == r)
return;
int q = int((p+r)/2);
merge_sort(array,p,q);
merge_sort(array,q+1,r);
//(p..q) and (q+1 .. r) sorted, then merge this two sorted array
int n1 = q-p+1;
int n2 = r-q;
cout << "Mark1 " <<n1<<' '<<n2<<endl;
int *array1;
array1 = new int(n1+1);
int *array2;
array2 = new int(n2+1);
for (int i=p; i<=q; i++)
array1[i-p] = array[i];
for (int i=q+1; i<=r; i++)
array2[i-q-1] = array[i];
array1[n1] = INT_MAX;
array2[n2] = INT_MAX; //CONSTANT, serve as sentinel
int p1 = 0;
int p2 = 0;
cout << "Mark2" << endl;
for (int i=p; i<=r; i++){
if (array1[p1]<array2[p2]){
array[i] = array1[p1];
p1++;
}else{
array[i] = array2[p2];
p2++;`enter code here`
}
}
cout << "Mark3" << endl;
delete [] array2;
cout << "Delete array2 " << endl;
delete [] array1;
cout << "Delete array1 " << endl;
}
The syntax
new int(n+1)
Creates a single int on the free-store and initialises it with n+1, and right away you access it out of bounds with array[1]. You want brackets:
new int[n + 1]
Which will create an array. The same goes for every other place like that in the program.
Also, since you are starting your loop at 1, the object array[0] is uninitialised and you get undefined behaviour if you access it, which you do. This is wasting an array element for nothing and setting up traps for yourself, I recommend you don't add 1 to the array size and start your indices from 0.