strdup() - what does it do in C?

前端 未结 10 2511
情话喂你
情话喂你 2020-11-21 23:22

What is the purpose of the strdup() function in C?

10条回答
  •  我在风中等你
    2020-11-22 00:13

    The statement:

    strcpy(ptr2, ptr1);
    

    is equivalent to (other than the fact this changes the pointers):

    while(*ptr2++ = *ptr1++);
    

    Whereas:

    ptr2 = strdup(ptr1);
    

    is equivalent to:

    ptr2 = malloc(strlen(ptr1) + 1);
    if (ptr2 != NULL) strcpy(ptr2, ptr1);
    

    So, if you want the string which you have copied to be used in another function (as it is created in heap section), you can use strdup, else strcpy is enough,

提交回复
热议问题