I dont really understand pointers and how to call and create dynamic arrays despite spending the time to educate myself on them and I am running into an error on the following line:
char *dArray = alphabet(N);
Here on my instructions and what Im trying to do:
- The program first asks user to enter the number of elements for an array. Let’s call this number N.
- It then creates a dynamic array of size N+ 1, containing Nrandom lowercase alphabet letters between ‘a’ and ‘z’. Make sure the last element is a null character ‘\0’. – Here, make sure to use dynamic memory allocation (using new command) to allocate memory space for the array, which is exactly why we call it a dynamic array.
- After creating the array, the program displays the entire array.
#include <stdio.h>
#include <iostream>
#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end
#include <ctime>
using namespace std;
char alphabet(int N)
{
char *dArray;
dArray= new char[N+1];
dArray[N]= '\0';
int i;
srand(time(NULL));
for (i=0; i<N; i++)
{
int r = rand()%26;
char letter='a'+r;
cout<<"dArray["<<i<<"] is: "<< letter<<endl;
dArray[i]= letter;
}
return *dArray;
}
int main()
{
int arrayN;
int N;
printf("enter the number of elements: ");
cin >> N;
char *dArray = alphabet(N);
for (int i=0; i<=N; i++)
{
cout<<"dArray["<<i<<"] "<<dArray[i]<<endl;
}
}
std::stringorstd::vectorinstead.alphabetnow is char, not char*return *dArray;means return the first character in the arraydArray. The pointer to the array is lost and without that pointer it's next to impossible to free the array. This is called a memory leak.<=in the exit condition of a loop iterating a container, odds are really good you are looking at a bug. Check the range ofiinfor (int i=0; i<=N; i++)to make certain you aren't going one past the end.