0
struct Person{
  char *name;
  int numb;
  char *var;
};

i have created a person above.

struct Person *per1=malloc(sizeof(struct Person));
char per1_name[]="leo";
per1->name=malloc(strlen(per1_name)+1);
strcpy(per1->isim,per1_name);
per1->numb=12;
char per1_var[]="Twitter";
per1->var=malloc(strlen(per1_var)+1);
strcpy(per1->var,per1_var);

and i always initialize it like that as you can see it is so long, so is there any easy way for intialization of struct type that contains string?

Leo S
  • 319
  • 2
  • 16
  • What's `per1->isim`? And your struct type does not contain any strings. It contains pointers to strings. This is how you declared it. – AnT stands with Russia Nov 21 '19 at 07:30
  • Actually, i have used this first but this problem has occured. https://stackoverflow.com/questions/58951732/initialization-of-string-in-struct/58951829?noredirect=1#comment104160732_58951829 @AnT – Leo S Nov 21 '19 at 07:32
  • Because of the requirement for dynamic allocation of two members, no, there isn't a short way to do this. Were those fixed buffers you could declare a struct with initial values, malloc a dynamic struct, then simply use struct-assignment. But, this is the road you chose, so... – WhozCraig Nov 21 '19 at 07:43
  • I got it. Thanks @WhozCraig – Leo S Nov 21 '19 at 07:44

2 Answers2

1

you can use macro to simplify/shorten your code. Also you can use separate function which initializes your structure.

struct Person{
  char *name;
  int numb;
  char *var;
};


#define MK_PERSON(per1, name, var, numb) \
struct Person *per1=malloc(sizeof(struct Person));\
per1->name=malloc(strlen(name)+1);\
strcpy(per1->name,name);\
per1->numb=numb;\
per1->var=malloc(strlen(var)+1);\
strcpy(per1->var,var);


struct Person * mk_person(const char *name, const char *var, int numb){
    struct Person *per1=malloc(sizeof(struct Person));
    per1->name=malloc(strlen(name)+1);
    strcpy(per1->name,name);
    per1->numb=numb;
    per1->var=malloc(strlen(var)+1);
    strcpy(per1->var,var);
    return per1;
}

int main(){

MK_PERSON(pers1, "Bob","m", 12);

struct Person *pers2 = mk_person("Mike", "m", 13);

}

this way you make/test and debug initialization only once and can use it safely later while being sure that everything is ok.

I recommend to use function instead macro.

Maxim Sagaydachny
  • 2,098
  • 3
  • 11
  • 22
1

You could write a function that initializes your struct:

void InitializePerson(struct Person *person, const char* name, int number, const char* var)
{
  person->name = strdup(person);
  person->var = strdup(var);
  person->numb = number;
}

int main()
{
  struct Person* per1 = malloc(sizeof(struct Person));
  InitializePerson(per1, "leo", 12, "Twitter");
}

This is just one of many possibilities. Also note that there is no error checking whatsoever for brevity.

if strdup is not available on your platform, you can write your own, it's basically 3 lines of code.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115