Home > Mobile >  [C]How to change value of input char* in a function
[C]How to change value of input char* in a function

Time:09-28

Below is my sample code.

void BTBasic_DLL_Call(char * functionName, char * parameters,  char * returnString, int * returnValue );

int _tmain(int argc, _TCHAR* argv[])
{
    char* fName = "connectProgrammer";
    char* parameter = "192.168.1.1";
    char* returnString ="0";
    int returnValue = 0;
    int n = 0;


    BTBasic_DLL_Call(fName,parameter,returnString,&returnValue);
    printf("%s \n", returnString);
    scanf("%d", n);

    return 0;
}

void BTBasic_DLL_Call(char * functionName, char * parameters,  char * returnString, int * returnValue )
{
    returnString = "DLL Test";
    *returnValue = 10;
}

In this code, I expect returnString would be changed as "DLL Test". But the printf result is still "0". Can anyone please help how to correctly read the changed returnString value?

CodePudding user response:

You can only set char * to a string literal at initialization. If you'd like to change this pointer to point to a different string literal, you'd have to pass it by pointer:

void BTBasic_DLL_Call(char * functionName, char * parameters, char ** returnString, int * returnValue) {
    *returnString = "DLL Test";
}

CodePudding user response:

Simple. The caller must pass the ADDRESS of the variable the function is to modify (just as you had done with the integer parameter).

// A function defined (ahead of use) is a function declared
// NB: Function receives address as "ptr to ptr"
void BTBasic_DLL_Call(char *functionName, char *parameters,  char **returnString, int *returnValue )
{
    functionName = functionName; // silence compiler warning
    parameters = parameters;

    *returnString = "DLL Test";
    *returnValue = 10;
}

//int _tmain(int argc, _TCHAR* argv[])
int main() // for demonstration 
{
    char *fName = "connectProgrammer";
    char *parameter = "192.168.1.1";
    char *returnString = NULL; // pointer initialised
    int returnValue = 0;

    // pass the address of the pointer
    BTBasic_DLL_Call( fName, parameter, &returnString, &returnValue );
    printf("%s \n", returnString);

    return 0;
}
DLL Test
  • Related