Char array as a function returned value

Joined
Nov 18, 2019
Messages
2
Reaction score
0
how to have a temporary char array in a function as its returned value?

like

char* nFunction(string& s){
const char* c=s.c_str();
char cn[9];
cn[0]=c[0];
cn[1]=c[1];
cn[2]=c[2];
return cn;

}
int main(){

string s("foo bar");
cout<<"return= "<<nFunction(s) ;
}


not work... what's the correct?
Thanks.
 
Last edited:
Joined
May 11, 2020
Messages
15
Reaction score
0
While I was searching I found this:
Code:
void testfunc(char* outStr){
  char str[10];
  for(int i=0; i < 10; ++i){
    outStr[i] = str[i];
  }
}

int main(){
  char myStr[10];
  testfunc(myStr);
  // myStr is now filled
}

But for the most secure conversion according to the results of my search you have to do as follows :

Code:
string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;

But it's to be verified I want to mislead you.
 
Joined
Jan 22, 2020
Messages
9
Reaction score
0
Hello, @maemaec
Please try this code, To Char array as a function returned value

C#:
char * createStr() {

    char char1= 'm';
    char char2= 'y';

    char *str = malloc(3);
    str[0] = char1;
    str[1] = char2;
    str[2] = '\0';

    return str;

}

When you call the function. So, you should have:

C#:
char *returned_str = createStr();

It worths mentioning that the returned value must be freed to prevent memory leaks.
C#:
free(returned_str);

I hope this code will be useful for you.
Thank you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top