'how to allocate memory int pointer array inside a function and delete the allocated memory in main.cpp
I am trying to allocate memory to a pointer to an array using a non-template type argument. But, I am getting a run time error at delete ptr in the main function.
#include <iostream>
using namespace std;
template<typename T, int SIZE>
void createArray(T** arrPtr) {
*arrPtr = new T[SIZE];
for (int i = 0; i < SIZE; i++)
(*arrPtr[i]) = i + 1;
}
int main()
{
constexpr int size = 3;
int* ptr = nullptr;
createArray<int, size>(&ptr);
if (ptr == nullptr)
return -1;
for (int i = 0; i < size; i++)
std::cout << *(ptr++) << " ";
delete ptr;
ptr = nullptr;
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
