Q:

How to iterate over a char pointer array returned by a function in cpp

I create a function that creates a 28 array from random chars from a-z.
When I try to iterate over the pointer array from main I get the wrong values.
What do I'm missing?
I know array are passed by reference to function, does are returned by reference too?
#include <iostream>
#include <ctime>
#define MAX 28

// Generate random char array with a-z values
char* generateRandomString(int length) {
    char random[length];
    for (int i = 0; i < length; i++) {
        // Minimun a ascii = 97
        // Maximun z ascii = 122
        srand(int(time(NULL))); // Timestamp seed generator
        int randomInt = 97 + (rand() % 25);
        char randomChar = randomInt;
        random[i] = randomChar;
    }
    return random;
}

int main() {
    char* random = generateRandomString(MAX);

    for (int i = 0; i < MAX; i++) {
        std::cout << random[i] << std::endl; // (*random)[i] Does not work neither
    }

    return 0;
}

A:

You are returning a pointer to a local variable that goes out of scope before the caller can use it.  Just use std::string instead.
And don't call srand() multiple times, call it only once.1
1: Even better, don't use srand() at all, use a C++ random number generator from the <random> library instead.
#include <iostream>
#include <string>
#include <ctime>
#define MAX 28

// Generate random char array with a-z values
std::string generateRandomString(int length) {
    std::string random;
    random.resize(length);
    for (int i = 0; i < length; i++) {
        // Minimun a ascii = 97
        // Maximun z ascii = 122
        int randomInt = 97 + (rand() % 25);
        char randomChar = randomInt;
        random[i] = randomChar;
    }
    return random;
}

int main() {
    srand(int(time(NULL))); // Timestamp seed generator

    std::string random = generateRandomString(MAX);

    for (int i = 0; i < MAX; i++) {
        std::cout << random[i] << std::endl; // (*random)[i] Does not work neither
    }

    return 0;
}

