Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 379
Andrey Khataev Avatar asked Feb 06 '26 14:02

Andrey Khataev


1 Answers

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);
like image 95
P.P Avatar answered Feb 09 '26 07:02

P.P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!