Search code examples
c++arraysfunctionpointersdynamic-arrays

how to return a dynamic char array from function C++


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:

  1. The program first asks user to enter the number of elements for an array. Let’s call this number N.
  2. 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.
  3. 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;
    }
}

Solution

  • you have declared the return type wrong. it should be char *

    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; // <<<<<<=====
    }
    

    but much better would be std::string or std::vector<char>