+ 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 :/

23rd Jan 2019, 6:44 PM
NoxFly
NoxFly - avatar
5 Antworten
+ 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");
23rd Jan 2019, 7:16 PM
Just4f
Just4f - avatar
+ 3
Thanks Just4f TheWhiteCat💡 even with it didnt work
23rd Jan 2019, 7:44 PM
NoxFly
NoxFly - avatar
+ 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(); }
24th Jan 2019, 5:53 AM
sree harsha
sree harsha - avatar
+ 1
You could try the following option: typedef struct { int dmg; char *name; } Weapon; ///////////// Weapon knife; knife.dmg = 40; knife.name = "knife";
28th Mar 2020, 1:17 AM
Arnold Ibarra
Arnold Ibarra - avatar
0
I think you should set the size of name char array => for example char name [20].
23rd Jan 2019, 7:11 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar