putting a character into a char pointer?

i've been trying to write a function that would return a char pointer which is made up of repeated characters.

The thing is i can only use c string function.

1
2
3
4
5
6
7
8
char* repeatedChar(char c, int numberOfRepetition)
{
    char *pChar;
    for(int i = 0; i < numberofRepetition; ++i)
        pChar += c;

    return pChar;
}


can anyone point out my mistake please? i am new to c++ and this char array thing kinda throw me off big time. Thank you
You don't initialize pChar.

Try this:
1
2
3
4
5
6
7
8
9
10
11
char* repeatedChar(char c, int numberOfRepetition)
{
    char *pChar = new char[numberOfRepetition+1]; // Allocates the correct amount of memory

    for(int i = 0; i < numberofRepetition; ++i)
        pChar[i] = c; // Puts the correct number of characters in the string

    pChar[numberOfRepetition] = '\0'; // Null-terminating the string

    return pChar;
}
Last edited on
A char pointer is just that: a pointer to a char sized memory location. So when you define

char* pChar;

You are just declaring a pointer object with no useful data in it. You'll need to do this:

char* pChar = new char;

This declares a char pointer that is filled with a useable object.

The problem is that the object is one byte in length, and you need more then that.

If you don't remeber, this is how you declare an array:

char* pChar = new char[];

With the number of elements in the brackets.
Last edited on
Topic archived. No new replies allowed.