c - Free first element of array -


when allocate array using malloc, there way free first element(s) of array?

a small example:

#include <stdlib.h> #include <string.h>  int main() {     char * = malloc(sizeof(char) * 8);     strcpy(a, "foo bar");      // how have this.     char * b = malloc(sizeof(char) * 7);     strcpy(b, a+1);       free(a);     free(b); } 

is there way free first char of a, can use rest of string using a+1?

if want remove first character of a, use memmove() move remainder of characters in string left 1, , use realloc() shrink allocation if desired:

#include <stdio.h> #include <stdlib.h> #include <string.h>  int main(void) {     char * = malloc(sizeof(char) * 8);     strcpy(a, "foo bar");      puts(a);      size_t rest = strlen(a);      memmove(a, a+1, rest);      /* if must reallocate */     char *temp = realloc(a, rest);     if (temp == null) {         perror("unable reallocate");         exit(exit_failure);     }     = temp;      puts(a);      free(a);      return 0; } 

update

@chux has made couple of good points in the comments.

first, instead of exiting on failure in realloc(), may better continue without reassigning temp a; after all, a point expected string anyway, allocated memory little larger necessary.

second, if input string empty, rest 0. leads problems realloc(a, rest). 1 solution check rest == 0 before modifying string pointed a.

here more general version of above code incorporates these suggestions:

#include <stdio.h> #include <stdlib.h> #include <string.h>  int main(void) {     char *s = "foo bar";     char *a = malloc(sizeof *a * (strlen(s) + 1));     strcpy(a, s);      puts(a);      size_t rest = strlen(a);      /* don't if empty string */     if (rest) {         memmove(a, a+1, rest);          /* if must reallocate */         char *temp = realloc(a, rest);         if (temp) {             = temp;         }     }      puts(a);      free(a);      return 0; } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -