Jump to content

strdup Function - C Programming


msp301
 Share

Recommended Posts

Hey, I'm trying to comment out some code of a small program I've got and have come across the function "strdup"; I've tried looking up how the function should be used, but can't find a well written description, would anyone be able to explain what this function is designed to do ?? Thanks :)

Link to comment
Share on other sites

If you're on linux go to a shell and type "man 3 strdup" or if you're on windows, go to google and type the same thing. It should give you the synopsis and description of what it does. It's basically like doing a call to malloc and then strcpy. Example:

#include <stdio.h>
#include <string.h>

int main()
{
     char* whatever="Hello\n";
     char* next=strdup(whatever); // Allocate enough memory for whatever to be copied to next and then put the value into it
     printf("%s",next);
}

This would do the same thing:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
        char* whatever="Hello\n";
        char* next=malloc((sizeof(char)*strlen(whatever))); // Alocate enough memory for whatever to go into next
        strcpy(next,whatever); // Put the value into next
        printf("%s",next);
}

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...