Pointer Function return string using C

Post date: May 6, 2011 11:21:34 AM

Scenario: some time we need a C function that need to return the string pointer.

   

    void GetConfigFile(char **path)

    {

        //String variable used to read the configuration file

        std::string configFile = "";

        if(0 != "C://")

        {

            configFile = "c://";

            //append the string at end of the exsisting one

            configFile.append("//conf//ConfigFile.xml");

        }

        else

        {

            configFile = "C://ConfigFile.xml";

        }

        //Allocating the memeory for the pointer

        *path= (char*) malloc(100*sizeof(char));

        //Copy the value from one to another.

        strcpy(*path, (char*) configFile.c_str());   

       

    }

Main method to calling that function

 int main(int argc, char **argv)

{

   

    //Create a char pointer

    char* path;

    GetConfigFile(&path) ;

    //Print the pointer values

     printf("%s", path);

    //Assign pointer to string varaible

    std::string strPath = path;

   //Print the string variable.

    printf("Config %s", strPath.c_str());

    getch();

}