C Programmers often requires obtaining a duplicate string from an original one. This can be achieved by knowing the length of the string and then allocating the buffer for the string and finally copying the content to the allocated buffer.

char * strdup(const char * str)
{
  int len;
  char * buffer;
  if(!str) {
    return NULL;
  }
  len = strlen(str);
10    buffer = (char *) malloc (len + 1);
11    strcpy(buffer, str);
12    return buffer;
13  }
14 

We do not require to do all the steps as C runtime library has strdup() function to do all these for us. Here is a sample example program.

#include <string.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
  int i = 0;
  const char *str = "A Quick Brown Fox Jumps over the lazy dog.";
  char *tokens, *token;
  tokens = strdup(str);
10    token = strtok(tokens, );
11    while(token) {
12      printf("Token %d: %s\n", i + 1, token);
13      token = strtok(NULL, " .");
14      i++;
15    }
16    free(tokens);
17    return 0;
18  }
19  Output:
20  Token 1: A
21  Token 2: Quick
22  Token 3: Brown
23  Token 4: Fox
24  Token 5: Jumps
25  Token 6: over
26  Token 7: the
27  Token 8: lazy
28  Token 9: dog
29 

Note: Buffer allocated by strdup should be released with free(). strtok(), strrev() etc are some utility functions modify its input buffer and produce the result. This is why we should not pass a constant string. CPU will produce a access violation while execution. strdup() is usedful for these cases.

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

multiple arguments in printf and scanf, strcpy and strcat source, memcpy vs memmove, strrev source, strdup, strtok, macro definition, C exception handling,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan