Ad
Algorithms
Strings

Include strdup() properly.
Remove unneeded index variable (passing intergral types as 'const' is just plan bizarre).

Code
Diff
  • #ifdef __STDC_ALLOC_LIB__
    #define __STDC_WANT_LIB_EXT2__ 1
    #else
    #define _POSIX_C_SOURCE 200809L
    #endif
    #include <stdlib.h>
    #include <string.h>
    
    /*
      Heap allocate the string and return it.
    */
    
    char* remove_string(const char *input, int n) {
      if (n <= 0 || input == NULL)
        return NULL;
    
      size_t len = 0;
      while (n--) {
        input += len;
        len = strlen(input);
        if (!len)
          return NULL;
        len++;
      }  
    
      return strdup(input);
    }
    • #ifdef __STDC_ALLOC_LIB__
    • #define __STDC_WANT_LIB_EXT2__ 1
    • #else
    • #define _POSIX_C_SOURCE 200809L
    • #endif
    • #include <stdlib.h>
    • #include <string.h>
    • /*
    • Heap allocate the string and return it.
    • */
    • char* remove_string(const char *input, const int n)
    • {
    • if (n <= 0 || input == NULL) return NULL;
    • for (size_t i = 0, len = 0; i < (size_t)n; i++)
    • {
    • char* remove_string(const char *input, int n) {
    • if (n <= 0 || input == NULL)
    • return NULL;
    • size_t len = 0;
    • while (n--) {
    • input += len;
    • if ((len = strlen(input) + 1) == 1) return NULL;
    • len = strlen(input);
    • if (!len)
    • return NULL;
    • len++;
    • }
    • return strdup(input);
    • }