1

I am currently learning dynamic memory allocation and came to find out that I have to store a string into a character pointer .

I have a structure Character.

struct Character{
char *name;
name = (char*) malloc(40*sizeof(char));
int Level;
long XP;
struct Inventory inventory;
};

The scope of the above structure is global.

I also have a function which takes pointer to structure and takes the input of the structure member.

void createCharacter(struct Character* b){
printf("Enter Name:");
scanf("%s",b->(*name));
printf("Enter Level:");
scanf("%d",&(b->Level));
printf("Enter XP:");
scanf("%ld",&b->XP);
}

My question is how to store the value given by user to that pointer.

IcanCode
  • 509
  • 3
  • 16

2 Answers2

3

I would suggest you to dynamically allocated the memory inside your createCharacter function as such. Dynamically allocating the memory and dereferencing it using b (struct Character *).

By the way, there is syntax error in your code when you declare b->(*name) I have included the explanation in the comments

void createCharacter(struct Character* b){

b->name = malloc(40*sizeof(char));

printf("Enter Name:");
scanf("%s",b->name);     /* you do not need to b->(*name) here -> is equivalent to (*b).name*/
printf("Enter Level:");
scanf("%d",&(b->Level));
printf("Enter XP:");
scanf("%ld",&b->XP);

free(b->name); /* Remember to always free dynamic allocated memory */
}
Calmen Chia
  • 325
  • 1
  • 8
2

As mentioned in the comment section name = (char*) malloc(40*sizeof(char)); is not a correct C syntax in structure.

So change your structure to :

struct Character{
char *name;
int Level;
long XP;
struct Inventory inventory;
};

Now the assignment you wanted to do in the above structure can be done inside your function as

void createCharacter(struct Character* b){
printf("Enter Name:");
b->name = (char*) malloc(40*sizeof(char));
scanf("%s",b->name);
printf("Enter Level:");
scanf("%d",&(b->Level));
printf("Enter XP:");
scanf("%ld",&b->XP);
}

There was another syntax error in your code scanf("%s",b->(*name)); This is not the valid syantax. so change it according to your function

SInce you are dynamically allocating don't forget to free the memory. Seems like there will be more code in the program so you can use the free() to free the memory when you want.

Abhilekh Gautam
  • 648
  • 1
  • 11
  • 27