kampi
kampi

Reputation: 2484

What is the correct way to pass a struct to a function?

I have a struct, which i'd like to pass to a function. Obviousley i am making somethin wrong, since the output is always the same : (null)

Could someone please help me. Thanks!

typedef struct
{
    char * Value1;
    char * Value2;
} TESTSTRUCT, *PTESTSTRUCT;

BOOL MyFunction(PTESTSTRUCT TestStruct);
BOOL QueryData(char * String, char * Name);

int main ()
{
   TESTSTRUCT myStruct;
   ZeroMemory( &myStruct, sizeof( myStruct) );

   MyFunction( &myStruct );

   printf( "\nmyStruct.Value1    = %s", myStruct.Value1);
   printf( "\nmyStruct.Value2    = %s", myStruct.Value2 );
   if ( myStruct.Value1 != NULL ) LocalFree( myStruct.Value1);
   if ( myStruct.Value2 != NULL ) LocalFree( myStruct.Value2 );
}
BOOL MyFunction(PTESTSTRUCT TestStruct)
{
   //.....
   QueryData(TestStruct->Value1, TestStruct->Value2);
   //.....
}
QueryData(char * String, char * Name)
{
    // do some stuff
    LPTSTR szName = NULL;
    szName = ( LPTSTR )LocalAlloc( LPTR, dwData * sizeof( TCHAR ) );
    String = AllocateMemory(szName);
    LocalFree( szName );
    szName = NULL;
    // do some more work
    szName = ( LPTSTR )LocalAlloc( LPTR, dwData * sizeof( TCHAR ) );
    Name = AllocateMemory(szName);
    LocalFree( szName );
}
LPSTR AllocateMemory( LPSTR inputString )
{
LPSTR outputString = NULL;

outputString = ( LPSTR )LocalAlloc( LPTR, ( strlen( inputString ) + 1 ) * sizeof( CHAR ) );

if (outputString != NULL)
{
    lstrcpyA( outputString, inputString );
}

return outputString;
}

Upvotes: 0

Views: 54

Answers (2)

Wyzard
Wyzard

Reputation: 34581

Pointers in C are passed by value: the String and Name arguments in QueryData are local variables that are initially copies of the (null) pointers in the caller's TestStruct. Changing the local variables within QueryData does not change the values stored in the structure.

You need to pass QueryData either a pointer to the structure itself (i.e. QueryData(TestStruct)) or pointers to the two char* values stored within the structure (i.e. QueryData(&TestStruct->Value1, &TestStruct->Value2)), so that QueryData can change the contents of the structure itself.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409442

The problem is that you assign to the pointer in QueryData. Since C passes all arguments by value, the pointer is copied, and you only modify the local copy inside the QueryData function.

You need to emulate pass by reference (I say "emulate" because C doesn't have pass by reference), by passing a pointer, in your case passing a pointer to the pointer.

Something like:

BOOL QueryData(char ** String, char ** Name)
{
    ...
    *String = AllocateMemory(...);
    ...
    *Name = AllocateMemory(...)
    ...
}

Call it like

QueryData(&TestStruct->Value1, &TestStruct->Value2);

Upvotes: 3

Related Questions