access violation in pointer allocation - c++

I want to put random data into arr (pointer allocation). How can I put data into that dynamic allocation?
typedef unique_ptr<unique_ptr<int[]>[]> uniquePtr;
uniquePtr arr = make_unique<unique_ptr<int[]>[]>(size);
srand(time(NULL));
cout << "size: " << endl;
cin >> size;
int max = size * size;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
arr[i][j] = rand() % max; //error!
}
}
Type of arr[i][j] is int.
When I tried this code,
arr[i][j] = new int(rand() % max);
but, the error is
arr[i][j] is int type and new int(~) is int* type
I want to put random int data into arr allocation.

The problem is you did not dynamically allocate the second dimension.
#include <iostream>
#include <memory>
using namespace std;
int main() {
int size = 5;
typedef unique_ptr<unique_ptr<int[]>[]> uniquePtr;
uniquePtr arr = make_unique<unique_ptr<int[]>[]>(size);
srand(time(NULL));
cout << "size: " << endl;
cin >> size;
int max = size * size;
for (int i = 0; i < size; i++) {
// Dynamically allocate the row
arr[i] = make_unique<int[]>(size);
for (int j = 0; j < size; j++) {
arr[i][j] = rand() % max;
}
}
return 0;
}
I put this online here: https://ideone.com/llAvTD

Related

C++ Memory leak error when resizing C++ dynamic array

The code below converts lets say array 3,9,3 to sorted array of integers 3,3,3,3,3 by converting 9 into sum of maximum possible parts.
The link to code/algorithm used in this code is answered at
https://stackoverflow.com/a/75331557/21145472
I am struck in this C++ code. When I ran it yesterday it was fine but today it gives memory leak error when function resizeArray() is run third time.
Please help fix this memory leak
#include<cmath>
#include <algorithm>
#include <iterator>
using namespace std;
void resizeArray(int *orig, int size, int newSize) {
int *resized = new int[newSize];
for (int i = 0; i < size; i ++)
resized[i] = orig[i];
delete [] orig;
orig = resized;
}
int main(){
int n = 3;
int *arr = new int[n];
int arrLength = n;
arr[0] = 3;
arr[1] = 9;
arr[2] = 3;
int *arrSorted = new int[0];
int sortedArrayLength = 0;
int temp;
unsigned long long int limit = 10e4;
long long parts = 0;
int extra = 0;
int mainArrayIndex = 0;
for(int i = 0; i<n/2; i++){
temp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = temp;
}
for(int i = 0; i < n; i++){
parts = floor((arr[i] - 1) / (limit)) + 1;
limit = arr[i] / parts;
extra = arr[i] % parts;
for(int index = 0; index < extra; index++){
resizeArray(arrSorted, sortedArrayLength, sortedArrayLength + 1);
arrSorted[mainArrayIndex] = limit+1;
mainArrayIndex+=1;
sortedArrayLength+=1;
}
for(int index = 0; index < parts - extra; index++){
resizeArray(arrSorted, sortedArrayLength, sortedArrayLength + 1);
arrSorted[mainArrayIndex] = limit;
mainArrayIndex+=1;
sortedArrayLength+=1;
}
}
cout << "Array sorted steps taken" << " " << sortedArrayLength - arrLength;
cout << endl;
for(int i = 0; i < sortedArrayLength; i++){
if(i == 0)
cout << "[";
cout << arrSorted[i];
if(i < sortedArrayLength - 1)
cout << ", ";
if(i == sortedArrayLength - 1)
cout << "]";
}
delete []arr;
delete []arrSorted;
}
Your helper function's orig = resized; doesn't reassign your main function's arrSorted as you intend. Use a reference:
void resizeArray(int *&orig, ...) {
(That and the lack of including iostream are the only correctness issues I see, and this fix got rid of the error.)

Sorting a list with indexes of another

I am trying to sort a list of indexes based on a list of string, and I receive bellow error - Segmentation fault. I cannot understand why I receive this error and how to solve it?
#include <iostream>
#include <string.h>
using namespace std;
int main() {
int size = 5;
char* mass[size];
int num[size];
for(int i = 0; i < size; i++) {
mass[i] = new char[20];
num[i] = i;
cin >> mass[i];
}
for(int i = 0; i < size; i++){
for(int j = size; j > i; j--)
if(strcmp(mass[num[j-1]], mass[num[j]]) > 0){
int tmp = num[j-1];
num[j-1] = num[j];
num[j] = tmp;
}
}
for(int i = 0; i < size; i++){
cout << mass[num[i]] << ", ";
}
return 0;
}
In the inner loop you start with j = size and then num[j] is an out-of-bounds array access.
In modern C++ you would solve this like this:
#include <iostream>
#include <array>
#include <algorithm>
int main() {
const int size = 5;
std::array<std::string, size> mass;
std::array<int, size> num;
for (int i = 0; i < size; i++) {
std::cin >> mass[i];
num[i] = i;
}
std::ranges::sort(num, [mass](int a, int b) { return mass[a] <= mass[b];});
for(int i = 0; i < size; i++){
std::cout << mass[num[i]] << ", ";
}
std::cout << std::endl;
return 0;
}

I am unable to get my code to get the stride of 7 to work properly C++

The question I am trying to solve is the following:
Write a function that traverses (and prints) the element of an array with stride =7. To do this the update part in the loop will be i= (i+7) % n, where n is the array size.
Would this function visit all elements of the array? Try different array sizes to check when it is impossible to traverse all elements.
The code that I wrote below doesn't print the correct values in the arry even if the value of i is correct.
Can anyone help, I would really appreciate it.
#include <fstream>
#include <stdlib.h>
using namespace std;
int* CreateArray(int n);
void StrideArray(int arr[], int n);
int main()
{
int* arr = new int[3];
arr = CreateArray(3);
cout << "The Elements In The Array Are: " << endl;
for (int i = 0; i < 3; i++)
{
cout << arr[i] << " ";
}
cout << endl;
StrideArray(arr, 3);
cout << "The Elements In The Array Stride 7 Are: " << endl;
for (int i = 0; i < 3; i++)
{
cout << arr[i] << " ";
}
delete[] arr;
return 0;
}
int* CreateArray(int n)
{
int* arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = (rand() % 100);
}
return arr;
}
void StrideArray(int arr[], int n)
{
int i = 0;
for (int j = 0; j < n; j++)
{
i = (i + 7) % n;
arr[j] = arr[i];
}
}
The problem is in StrideArray you read back the modified values of arr.
void StrideArray(int arr[], int n)
{
int i = 0;
int puffer=new int[n];
for (int j = 0; j < n; j++)
{
i = (i + 7) % n;
puffer[j] = arr[i];
}
for (int j = 0; j < n; j++){
puffer[j] = arr[j];
}
debete[] puffer;
}
Is a good way to write the function.
Also it visits all element only if n isn't dividable by 7. So if n is not 7,14,21,...
Also to use cout you have to #include <iostream>
Your StrideArray function needs fixing; you are iterating over j but using i to index, which remains constant; and you are reassigning value at one index to another where as you are supposed to print it:
void StrideArray(int arr[], int n)
{
int i = 0;
for (int j = 0; j < n; j=j+7)
{
cout << arr[j] << endl;
}
}
I modified the rest of your code for demo:
#include <iostream>
#include <stdlib.h>
using namespace std;
int* CreateArray(int n);
void StrideArray(int arr[], int n);
int main()
{
int* arr = new int[3];
arr = CreateArray(21);
cout << "The Elements In The Array Are: " << endl;
for (int i = 0; i < 21; i++)
{
cout << arr[i] << " ";
}
cout << endl;
StrideArray(arr, 21);
delete[] arr;
return 0;
}
int* CreateArray(int n)
{
int* arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = (rand() % 100);
}
return arr;
}

I'm trying to print my array but i'm not getting my desired result

I'm fairly new to programming and was trying to create a program which creates a one dimensional array with random numbers from a certain range and then prints it out. I managed to make a function to create the array but I'm having trouble actually printing out the array I made. I have a general idea of what the problem might be but no clue as to how to fix the code.
Here is the code in question:
#include <iostream>
using namespace std;
int *create(int n)
{
int *arr = new int [n];
for (int i = 0; i > n; i++)
{
arr[i] = rand() % 100;
}
}
int main ()
{
int n = 12;
int *arr = create(n);
cout << "this is the array: ";
for (int i = 0; i > n; i++)
{
cout << arr[i] << " ";
};
delete[] arr;
return 0;
}
There are two errors in your code:
You are not returning your array from create()
Your loop condition is incorrect.
Fixed code:
#include <iostream>
using namespace std;
int *create(int n)
{
int *arr = new int [n];
for (int i = 0; i < n; i++)
{
arr[i] = rand() % 100;
}
return arr;
}
int main ()
{
int n = 12;
int *arr = create(n);
cout << "this is the array: ";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
};
delete[] arr;
return 0;
}
I dont see how you code compiles.
You are not returning anything from function.
both your loop conditions should be <n
This way is works but your design is very poor, unless you are just learning handling pointers.
#include <iostream>
using namespace std;
int* create(int n)
{
int* arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = rand() % 100;
}
return arr;
}
int main()
{
int n = 12;
int* arr = create(n);
cout << "this is the array: ";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
};
delete[] arr;
return 0;
}
The only missing part in your code - you are not returning your arr variable from your create function.
int *create(int n)
{
int *arr = new int [n];
for (int i = 0; i > n; i++)
{
arr[i] = rand() % 100;
}
return arr;
}
This way it will work:)
You made a mistake in the loop. you used '>' instead of '<' line 22 should be.
for (int i = 0; i < n; i++)
The loop stopped before the first iterations because i=0 was smaller than n=12.

Sorting an array from Largest to smallest in C++

I wanna sort an array from largest to smallest number and make a new array which has it sorted...
so here is my code:
#include <iostream>
using namespace std;
int main()
{
int size, sum = 0, answer = 0,pos, max;
int array[size];
int array2[size];
cin >> size;
for (int i = 0; i < size; i++)
{
cin >> array[i];
sum+=array[i];
}
for (int i = 0; i < size; i++)
{
max = 0;
pos = 0;
for (int q = 0; q < size; q++)
{
if (array[q] > max)
{
max = array[q];
pos = q;
}
}
array2[i] = max;
array[pos] = 0;
}
for (int i = 0; i < size; i++)
{
cout << array2[i] << ", ";
}
return 0;
}
When I put my input:
5
1 2 3 4 5
The output I get is:
0, 0, 0, 0, 5,
but I expect it to be 5, 4, 3, 2, 1,
First of all always initialize a variable when you create it as by default it has some garbage value in C++,
Also you are trying to assign a size variable (as size for an array) that has nothing assign to it yet which will create problems, Secondly you are initializing an array first and then you are taking the size variable from user which is completely opposite of the flow, for creating arrays with dynamic size see How Dynamic Array works and is implemented in C++
Updated Code:
#include <iostream>
using namespace std;
int main()
{
int size=0, sum = 0, answer = 0,pos, max;
cin >> size;
int array[size];
int array2[size];
for (int i = 0; i < size; i++)
{
cin >> array[i];
sum+=array[i];
}
for (int i = 0; i < size; i++)
{
max = 0;
pos = 0;
for (int q = 0; q < size; q++)
{
if (array[q] > max)
{
max = array[q];
pos = q;
}
}
array2[i] = max;
array[pos] = 0;
}
for (int i = 0; i < size; i++)
{
cout << array2[i] << ", ";
}
return 0;
}
Here is the Output
Edit:
As Per #PaulMcKenzie method, the other way which is considered the appropriate one, uses the std::Vector method to initialize a dynamic array in C++, people who use the first method in visual studio might face errors,
Second Method Updated Code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int size=0, sum = 0, answer = 0,pos, max;
cin >> size;
std::vector<int> array(size), array2(size);
for (int i = 0; i < size; i++)
{
cin >> array[i];
sum+=array[i];
}
for (int i = 0; i < size; i++)
{
max = 0;
pos = 0;
for (int q = 0; q < size; q++)
{
if (array[q] > max)
{
max = array[q];
pos = q;
}
}
array2[i] = max;
array[pos] = 0;
}
for (int i = 0; i < size; i++)
{
cout << array2[i] << ", ";
}
return 0;
}
Second Output
The size of an array variable must be a compile-time constant. A user-supplied value at runtime is probably unknowable at compile time.so I recommend using std::vector instead of array.
#include <iostream>
#include<vector>
#include <algorithm>
int main()
{
int size=0, input=0;
std::cout << "enter size :";
std::cin >> size;
std::vector<int> vec;
for (size_t i{ 0 }; i < size; ++i)
{
std::cout << "enter "<<i<< ".input:";
std::cin >> input;
vec.push_back(input);
}
// Sort the elements of the vector in descending order
for (const auto& i : vec)
std::sort(vec.begin(), vec.end(), std::greater <>());
//Print the elements of the vector
for (const auto& i : vec)
std::cout << i << " ,";
return 0;
}
Output:
enter size :5
enter 0.input:1
enter 1.input:2
enter 2.input:3
enter 3.input:4
enter 4.input:5
5 ,4 ,3 ,2 ,1 ,