EquipDev
EquipDev

Reputation: 5931

How to create and return string from function?

Would like to generate a string from a function, in order to format some data, so the function should return a string.

Tried to do the "obvious", shown below, but this prints garbage:

#include <iostream>
#include <string>

char * hello_world()
{
    char res[13];
    memcpy(res, "Hello world\n", 13);
    return res;
}

int main(void)
{
    printf(hello_world());
    return 0;
}

I think this is because the memory on the stack used for the res variable, defined in the function, is overwritten before the value can be written, maybe when the printf call uses the stack.

If I move char res[13]; outside the function, thus makes it global, then it works.

So is the answer to have a global char buffer (string) that can be used for the result?

Maybe doing something like:

char * hello_world(char * res)
{
    memcpy(res, "Hello world\n", 13);  // 11 characters + newline + 0 for string termination
    return res;
}

char res[13];

int main(void)
{
    printf(hello_world(res));
    return 0;
}

Upvotes: 1

Views: 1521

Answers (4)

Eduardo Fernandes
Eduardo Fernandes

Reputation: 403

Still, if you want to write a pure C code, will can do something like that.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *HelloWorld(char *s, int size)
{
        sprintf(s, "Hello world!\n");
        return s;
}

int main (int argc, char *argv[])
{
        char s[100];

        printf(HelloWorld(s, 100));

        return 0;
}

Upvotes: 1

mahesh
mahesh

Reputation: 1098

Best solution would be to use std::string. However, if you must use an array, then it is best to allocate it in the calling function (in this case, main()):

#include <iostream>
#include <cstring>

void hello_world(char * s)
{
    memcpy(s, "Hello world\n", 13);
}

int main(void)
{
    char mys[13];
    hello_world(mys);
    std::cout<<mys;
    return 0;
}

Upvotes: 2

nvoigt
nvoigt

Reputation: 77304

You are programming . That's not bad, but your question is about so this is the solution for the question you asked:

std::string hello_world()
{
    std::string temp;

    // todo: do whatever string operations you want here
    temp = "Hello World";

    return temp;
}

int main()
{
    std::string result = hello_world();

    std::cout << result << std::endl;

    return 0;
}

Upvotes: 5

MSalters
MSalters

Reputation: 179917

Don't bother with that early-20th century stuff. By the end of the previous century we already had std::string, and that's straightforward:

#include <iostream>
#include <string>

std::string hello_world()
{
    return "Hello world\n";
}

int main()
{
    std::cout << hello_world();
}

Upvotes: 9

Related Questions