array won't properly display

ok so I have a program that is supposed to randomly generate a character array, count each letter in the array, display the array, then display the count for each character. It works fine, except when it displays the array, it displays a single character, then a lot of random garbage. this is the code for it. i put the entire code because I don't know if it's the function in bold causing the issue of something else i've done.



#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;

int num;
char *cp;
char *createArray(int);
char getLowerCaseLetter();
int *countLetters();
int displayLetters(char *, int);
int displayCount();

int main()
{
srand(time(0));
cout << "Enter an integer to set the array size: ";
cin >> num;
char * ap;
ap = createArray(num);
displayLetters(ap, num);
}

char getLowerCaseLetter()
{
return (char) ('a'+ rand()%25);
}

char *createArray(int num)
{
char character[num];
cp = &character[num];
for (int ix = 0; ix < num; ix++)
{
getLowerCaseLetter();
*(cp + ix) = getLowerCaseLetter();
}
return cp;
}

int countLetters(char * cp, int num)
{
for(int j = 0; j < num; j++)
{
char letter = *cp;
int count = 0;
for (int k = 0; k < num; k++)
{
if (letter = *cp)
count++;
}
cout << "The letter " << letter << " appeared " << count << " times.\n";
}
}

int displayLetters(char * cp, int num)
{
for (int m = 0; m < num; m++)
{
cout << *(cp+m) << " ";
}
}

Your createArray() function only creates an array temporarily. It disappears when the function ends.

Why is cp global? This won't make the array it points to in the createArray() global. char* cp may as well be local to createArray.

A quick fix may be to replace cp = &character[num];
with cp = new char[num]; in createArray.
Topic archived. No new replies allowed.