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.
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.
For my lab in school I was asked to generate random numbers and characters and pass it into a function template and then sort them after showing my work as unsorted first. I'm using visual studios as a requirement for my school, but my main issue is that it's compiling with no errors but when I run my program it's not passing my array to be sorted. I've been spending a lot of time trying to understand why it's not working any help would be very appreciated.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
template <typename T>
void arrayIn(T arr[], int size, char word) {
if (word == 'd') {
sort(arr, arr + size, greater<>());
}
else {
sort(arr, arr + size);
}
return;
}
template <typename O>
void arr_out(O arr[], int size) {
int j;
for (j = 0; j < size; j++) {
cout << arr[j] << endl;
return;
}
delete[] arr;
}
int main(void) {
srand(time_t(NULL));
int size,i,j;
char word;
int *arr1;
char *arr2;
cout << "Enter in the size of the array: ";
cin >> size;
cout << "How would you like to sort in ascending or descending order?: ";
cin >> word;
arr1 = new int[size];
arr2 = new char[size];
if (arr1 == 0) {
cout << "memory allocation error";
system("pause");
exit(1);
}
cout << "The first array will sort intagers." << endl;
cout << "not sorted" << endl;
for (i = 0; i < size; i++) {
arr1[i] = rand() % 100 + 1;
cout << arr1[i] << endl;
}
arrayIn(arr1, size, word);
cout << "sorted" << endl;
arr_out(arr1,size);
if (arr2 == 0) {
cout << "memory allocation error";
system("pause`enter code here`");
exit(1);
}
cout << "the secound array will sort characters." << endl;
cout << "not sorted" << endl;
for (j = 0; j < size; j++) {
arr2[j] = rand() % (126 + 1 - 33) + 33;
cout << arr2[j] << endl;
}
arrayIn(arr2, size, word);
cout << "sorted" << endl;
arr_out(arr2, size);
system("pause");
return 0;
}
You have a very simple mistake in your arr_out function, which makes it only print the first element. Correct as follows (remove the line I commented out):
template <typename O>
void arr_out(O arr[], int size) {
int j;
for (j = 0; j < size; j++) {
cout << arr[j] << endl;
// return; // This will return after printing the first element!
}
delete[] arr;
}
I have this code of a dynamic array that I turned in as a lab. My instructor responded saying "wouldn't even compile, no resize of the array". I am having trouble dealing with the comment of "no resize of the array", meaning I have to add the ability to resize the array. Please help quick! (It does compile). Appreciate it.
I am supposed to make a program that asks the user to initially size the array. Create an array based on that size asking for a number, and insert the number. Then repeat getting and inserting a number, resizing the array as needed or until they enter -1 for the number.
Print the list.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int count;
cout << "How many values do you want to store in your array?" << endl;
cin >> count;
int* DynamicArray;
DynamicArray = new int[count];
for (int i = 0; i < count; i++) {
cout << "Please input Values: " << endl;
cin >> DynamicArray[i];
{
if (DynamicArray[i] == -1) {
delete[] DynamicArray;
cout << "The program has ended" << endl;
exit(0);
}
else {
cout << endl;
}
}
}
for (int k = 0; k < count; k++) {
cout << DynamicArray[k] << endl;
}
delete[] DynamicArray;
return 0;
}
When the array is full, we need to resize it. Here is my solution
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
int count;
cout << "How many values do you want to store in your array?" << endl;
cin >> count;
if (count <= 0) {
cout << "The value should be greater than zero" << endl;
exit(0);
}
int* DynamicArray;
DynamicArray = new int[count];
int i = 0, value = 0;
while (1) {
cout << "Please input Values: " << endl;
cin >> value;
if (value == -1) {
cout << "The program has ended" << endl;
break;
}
else if (i < count)
{
DynamicArray[i++] = value;
}
else
{
// resize the array with double the old one
count = count * 2;
int *newArray = new int[count];
memcpy(newArray, DynamicArray, count * sizeof(int));
delete[]DynamicArray;
newArray[i++] = value;
DynamicArray = newArray;
}
}
for (int k = 0; k < i; k++) {
cout << DynamicArray[k] << endl;
}
delete[] DynamicArray;
return 0;
}
I am using a int pointer as private to access an array. When i write separate functions for store and get values to an array, the program crashes. But if i write the get value and store value code in constructor, the program works fine. I am not able to find where the problem is.
Program 1: (Which is not working)
#include<iostream>
using namespace std;
class NewArray{
private:
int Size = 0;
int *arrAddr = NULL;
public:
NewArray(int);
void SetValue(int);
void GetValueOf(int);
};
//Array is created
NewArray::NewArray(int arSz){
int arr[arSz];
Size = arSz;
arrAddr = arr;
cout << "An array of Size " << Size << " is created" << endl;
}
// Store Value function
void NewArray::SetValue(int index)
{
cin >> *(arrAddr+(index));
}
//Get value function
void NewArray::GetValueOf(int idx)
{
if ((idx >= Size) || (idx < 0))
{
cout << "index value is out of bound" << endl;
}
else
{
cout << *(arrAddr+idx) << endl;
}
}
int main()
{
int arrSize, arrIdx;
cout << "enter the size of array" << endl;
cin >> arrSize;
if (arrSize > 0)
{
NewArray ar(arrSize);
cout << "enter " << arrSize << " values. Enter the values one after the other." << endl;
for (int i = 0; i < arrSize; i++)
{
ar.SetValue(i);
ar.GetValueOf(i);
}
cout << "enter the index to fetch the value" << endl;
cin >> arrIdx;
ar.GetValueOf(arrIdx);
}
else{
cout << "invalid input" << endl;
}
return 0;
}
Program 2: (Code which is working)
#include<iostream>
using namespace std;
// size is passed
class NewArray{
private:
int Size;
int *arrAddr;
public:
NewArray(int);
void GetValueOf(int);
};
NewArray::NewArray(int arSz){
int arr[arSz];
int idx;
Size = arSz;
arrAddr = arr;
cout << "An array of Size " << Size << " is created" << endl;
// Storing values in array
cout << "enter " << Size << " values. Enter the values one after the other." << endl;
for (int i = 0; i < Size; i++)
{
cin >> *(arrAddr+i);
}
// To get the value from the index
cout << "enter the index to fetch the value" << endl;
cin >> idx;
if ((idx >= Size) || (idx < 0))
{
cout << "index value is out of bound" << endl;
}
else
{
cout << "The value is " << *(arrAddr+idx) << endl;
}
}
int main()
{
int arrSize, arrIdx;
cout << "enter the size of array" << endl;
cin >> arrSize;
if (arrSize > 0)
{
NewArray ar(arrSize);
}
else{
cout << "invalid input" << endl;
}
return 0;
}
I have tried for this particular example, program 1 crashes when the array size is 10 and when i am trying to write to 7th index.
Can anyone please help me find out why?
In the constructor NewArray::NewArray() you create an array, which is stored on the stack. After leaving the constructor its lifetime is over, it is removed from the stack, so accessing it through your pointer arrAddr is Undefined Behavior.
To simply fix the problem you need to allocate the array on the heap using new and delete or store it as a class member.
These are just two ways of implementing. I do not recommend anything, they are just possibilities.
int arr[arSz];
is allocated on stack and hence it's lifetime is limited to the function in which it is defined - the allocated stack memory is available for others once the stack is unwound. You need to allocate memory on heap using the new operator, for the memory to remain persistent after the function call.
arrAddr = new int[arSz];
The above allocates memory on heap and is available until explicitly deleted by a call to delete [] arrAddr, which in most cases should be done only in the destructor.
forgot about int *. use vector instead. look here
#include <iostream>
#include <conio.h>
#include <vector>
using namespace std;
class Class1 {
private:
vector<int> intArr;
public:
void Set(int iValue) {
intArr.push_back(iValue);
}
int Get(int iIndex) {
return intArr[iIndex];
}
};
int main() {
Class1 class1;
for (size_t i = 0; i < 10; i++)
{
class1.Set(i);
}
for (size_t i = 0; i < 10; i++)
{
cout << class1.Get(i) << endl;
}
_getch();
}