+ 2
C struct
typedef struct Weapon { int dmg; char name[]; } Weapon; //////////// Weapon knife; knife.dmg = 40; // all good knife.name = "knife" // expression must be a modifiable value Help :/
5 Answers
+ 2
knife.name = malloc(sizeof(char) * 6);
knife.name[5] = '\0';
strcpy(knife.name, "knife");
Or easier
typedef struct Weapon {
int dmg;
char name[50];
};
Weapon knife;
strcpy(knife.name, "knife");
+ 3
Thanks Just4f
TheWhiteCatđĄ even with it didnt work
+ 1
struct struturename
{
datamember1,
datamember2,
â
â
}variable;
structure is a collection of heterogeneous datatypes
The variables in structures are datamembers
Every structure must have a variable called struture variable
if it is normal variable use dot(.) operator to access structure variables
if it is pointer use arrow(->) opreator to access structure variables
structure with in structure is called nested structure
ex:
struct student
{
int sno;
char sname[30];
};
void main()
{
struct student s;
struct student *p;
clrscr();
printf(âEnter no :â);
scanf(â%dâ,&s.sno);
printf(âEnter name :â);
scanf(â%sâ,s.sname);
printf(âNumber = %d\nâ,s.sno);
printf(âName = %s\nâ,s.sname);
printf(â\nâ);
printf(âEnter no :â);
scanf(â%dâ,&p->sno);
printf(âEnter name :â);
scanf(â%sâ,p->sname);
printf(âNumber = %d\nâ,p->sno);
printf(âName = %s\nâ,p->sname);
getch();
}
+ 1
You could try the following option:
typedef struct {
int dmg;
char *name;
} Weapon;
/////////////
Weapon knife;
knife.dmg = 40;
knife.name = "knife";
0
I think you should set the size of name char array => for example char name [20].