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);
  buffer = (char *) malloc (len + 1);
  strcpy(buffer, str);
  return buffer;
}

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);
  token = strtok(tokens, );
  while(token) {
    printf("Token %d: %s\n", i + 1, token);
    token = strtok(NULL, " .");
    i++;
  }
  free(tokens);
  return 0;
}
Output:
Token 1: A
Token 2: Quick
Token 3: Brown
Token 4: Fox
Token 5: Jumps
Token 6: over
Token 7: the
Token 8: lazy
Token 9: dog

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.

About our authors: Team EQA

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

#