How can I assign values to struct member character by character. I would like to do something 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 i = 0;
while (*a != '\0') {
if (*a == '-')
i++;
else ss[i].z = *a; // can I do this?
a++;
}
for(i = 0; i<2; i++)
printf("%s\n",ss[i].z);
}
So I can get something as:
ss[0].z = "Hello World"
ss[1].z = "-Bye Foo Bar"
Edit: Forgot to mention, the number of “-” in str might vary.
If
const char *strwasn’t const you could insert a'\0'to split the string into two. You’d need to shift the other chars to the “right” as well in doing so.The cleaner solution is to use something like
strdupto make two copies of the string, one of which you terminate early, the other of which you start the copy partway through:e.g.
Update: You can use this, even with more than one ‘-‘
In practice you want to be more careful to avoid bugs with unexpected inputs so you need to be sure you handle:
Don’t forget to
free()too!