euskadi
euskadi

Reputation: 127

Wrong info returning from a function

I have a problem at using a function that returns a char. This is the code of the function, which gathers 3 chars(c1,c2,c3) into 1 (infotot):

char gatherinfo(char *c1,char *c2,char *c3){
    char infotot[256];
    int n=sprintf(infotot,"%s;%s;%s;",c1,c2,c3);
    return *infotot;
}

And in main I have this code in order to access to the function:

char info[256];
    *info=gatherinfo(c1,c2,c3);

Where c1, c2, and c3 are defined as:

char *c1,*c2,*c3;

In the function, infotot takes the right value:

*infotot="c1;c2;c3;"

But the problem comes in main, where info takes the following value;

*info="lÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ"

Where the first letter "l" corresponds to the first letter of c1. How could I solve it in order to have info="c1;c2;c3;"?

Upvotes: 1

Views: 65

Answers (3)

Alessandro Pezzato
Alessandro Pezzato

Reputation: 8802

gatherinfo is returning a single char, not a string. You are assigning that char to the first element of the array info.

This array isn't null terminated, so when you print it, you see the first element followed by garbage.

You must return a std::string. A std::string can be copied.

std::string gatherinfo(char *c1,char *c2,char *c3){
    char infotot[256];
    sprintf(infotot,"%s;%s;%s;",c1,c2,c3);
    return infotot; // Here infotot is used to construct the std::string returned by the function. Same as return std::string(infotot);
}

You can also use the std::string operator + (concatenation)

std::string gatherinfo(char *c1,char *c2,char *c3){
    return std::string(c1) + ";" + c2 + ";" + c3 + ";";
}

Upvotes: 4

gatherinfo returns a single character (not a string of characters).

You write this single character (which will be the first char of c1) into the first character of info - but critically, you don't write a null character afterwards.

The fix is that gatherinfo should return std::string. (And I suspect that it should take it's arguments as const std::string& too). So:

std::string gatherinfo(
   const std::string& c1, const std::string& c2, const std::string& c3){
    return c1 + ';' + c2 + ';' + c3
}

Upvotes: 0

alain
alain

Reputation: 12047

char infotot[256]; will be deallocated when gatherinfo returns.

I would allocate the destination buffer in main and pass it to the function:

char info[256];
gatherinfo(info,c1,c2,c3);

void gatherinfo(char *infotot,char *c1,char *c2,char *c3){
    sprintf(infotot,"%s;%s;%s;",c1,c2,c3);
}

To improve this, you could use std::string.

Upvotes: 1

Related Questions