msp301 Posted April 13, 2009 Share Posted April 13, 2009 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 :) Quote Link to comment Share on other sites More sharing options...
Jonnycake Posted April 15, 2009 Share Posted April 15, 2009 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); } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.