Search code examples
cpointersstructfunction-parameter

struct's string field as function's parameter in C


I have a struct

typedef struct HASH_NODE
{
    char*              word;
    struct HASH_NODE*  next;
} HASH_NODE;

and function

void foo(char* destptr, const char* srcptr)
{
    destptr = malloc(strlen(srcptr)+1);
    strcpy(destptr, srcptr);
}

I want to pass structs field .word to foo and I expect that value of my field would be changed after function return, but it doesn't:

int main (void)
{
    HASH_NODE* nodeptr = malloc(sizeof(HASH_NODE));
    nodeptr->next = NULL;
    nodeptr->word = NULL;
    char* word = "cat";
    foo(nodeptr->word, word);
}

What am I doing wrong?


Solution

  • You are overwriting the pointer destptr passed to foo() by malloc'ing. Pass a pointer to pointer from main() to foo():

    void foo(char** destptr, const char* srcptr)
    {
        *destptr = malloc(strlen(srcptr)+1);
        strcpy(*destptr, srcptr);
    }
    

    and call as:

    foo(&nodeptr->word, word);