struct member character by character in c -


how can assign values struct member character character. like

#include <stdio.h> #include <stdlib.h> #include <string.h>  struct s {     char  *z;  };  int main () {     struct s *ss;    ss = malloc(2 * sizeof *ss);     char *str = "hello world-bye foo bar";    char *a = str;    int = 0;    while (*a != '\0') {        if (*a == '-')            i++;        else ss[i].z = *a; // can this?        a++;    }       for(i = 0; i<2; i++)       printf("%s\n",ss[i].z); } 

so can as:

ss[0].z = "hello world" ss[1].z = "-bye foo bar" 

edit: forgot mention, number of "-" in str might vary.

if const char *str wasn't const insert '\0' split string two. you'd need shift other chars "right" in doing so.

the cleaner solution use strdup make 2 copies of string, 1 of terminate early, other of start copy partway through:

e.g.

ss[0].z = strdup(str); ss[1].z = strdup(strchr(str, '-')); const size_t fist_part = strlen(str)-strlen(ss[1].z); ss[0].z[first_part] = 0; 

update: can use this, more 1 '-'

#include <stdio.h> #include <stdlib.h> #include <string.h>  struct s {     char  *z;  };  int main () {   struct s *ss;   ss = malloc(20 * sizeof(struct s));    const char *str = "hello world-bye foo bar-more-and-more-things";   int = 1;   char *found = null;   ss[0].z = strdup(str);   while ((found = strchr(ss[i-1].z, '-'))) {      // todo: check found+1 valid!      ss[i].z = strdup(found+1);      *found = 0;      ++i;   }      for(i = 0; i<6; i++)      printf("%s\n",ss[i].z);    return exit_success; } 

in practice want more careful avoid bugs unexpected inputs need sure handle:

  • there no '-' char
  • there no '\0' char
  • allocation failure

don't forget free() too!


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -