returning a char array from a char function in c++

I am doing this

char *draw_line(int n, char ch)
{
    char *line = new char[50];
    for(int i = 0; i <= n; i++)
        line[i] = ch;
    return line;
}

and while calling the function I am writing this:

char *res_line = draw_line(50, '=');
cout<<*res_line;

but instead of getting = printed 50 times in the console window, it just show = sign one time. My main aim is to return the = or any character as many times I want and output the same to a text file. That's it.

Upvotes: 1

Views: 154

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361254

cout<<*res_line;

is printing one char because *res_line is char, not char*.

Write:

cout<<res_line; 

But wait — that is not going to work either because res_line is NOT null-terminated.

Use std::string or std::vector<char>avoid explicit memory allocation, use RAII idiom instead:

std::string draw_line(int n, char ch)
{
    return {n, ch}; //C++11
}

So simple!

Or if you use std::vector:

std::vector<char> draw_line(int n, char ch)
{
    return {n, ch}; //C++11
}

which is almost same.

In C++03, however, you've to write:

return std::string(n, ch);        //in the first case
return std::vector<char>(n, ch);  //in the second case

That is, invoke the constructor explicitly.

Upvotes: 5

firda
firda

Reputation: 3338

char* draw_line(int n, char ch)
{
    char *ch2= (char *) malloc(sizeof(char)*(n+1)); // (n+1) here
    for(int i=0;i<n;i++) // < instead of <=
        ch2[i]=ch;
    ch2[n] = 0; // terminator
    return ch2;
}

char *ch50 = draw_line(50,'=');
cout<< ch50; // changed from *ch50 to ch50

ADDON: look at string-fill constructor

cout << string(50, '=');

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

The valid code will look as

char* draw_line( int n, char ch )
{
    char *ch2= new char[n + 1]();

    std::memset( ch2, ch, n );

    return ch2;
}

//...

char *ch50 = draw_line(50,'=');
cout << ch50;
//...
delete []ch50;    

Take into account this statement

char *ch2= new char[n + 1]();

But it would be much better to write simply

std::cout << std::string( 50, '=' );

Upvotes: 2

Related Questions