Char array as a function returned value

Discussion in 'C Programming' started by maemaec, Nov 23, 2019.

  1. maemaec

    maemaec

    Joined:
    Nov 18, 2019
    Messages:
    2
    Likes Received:
    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: Nov 23, 2019
    maemaec, Nov 23, 2019
    #1
    1. Advertisements

  2. maemaec

    bryonmajor

    Joined:
    May 11, 2020
    Messages:
    15
    Likes Received:
    0
    While I was searching I found this:
    Code (C):
    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 (C):
    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.
     
    bryonmajor, May 13, 2020
    #2
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.