0

How do you assign a variable in one of the member construct in C?

I used the brackets after the name variable, but I still do not under stand why I am getting error messages. I know that C does not support string, but an array could be used to store string values: Here is my code: #include <stdio.h> struct Student{ char name[12]; int age; }; int main(){ struct Student s1; struct Student s2; s1.name[12] = "Shubham"; s1.age = 21; s2.name = "Gargi"; s2.age = 13; printf("\nName: %s \n Age: %d ",s1.name,s1.age); printf("\nName: %s \n Age: %d ",s2.name,s2.age); } Terminal: ERROR! gcc /tmp/65wVAJrLIS.c -lm /tmp/65wVAJrLIS.c: In function 'main': /tmp/65wVAJrLIS.c:13:17: warning: assignment to 'char' from 'char *' makes integer from pointer without a cast [-Wint-conversion] 13 | s1.name[12] = "Shubham"; | ^ /tmp/65wVAJrLIS.c:16:13: error: assignment to expression with array type 16 | s2.name = "Gargi"; |

19th Jun 2023, 6:11 PM
Shubham Ambekar
Shubham Ambekar - avatar
3 odpowiedzi
+ 3
Shubham Ambekar just use a char* for name. #include <stdio.h> struct Student{ char* name; int age; }; int main(){ struct Student s1; struct Student s2; s1.name = "Shubham"; s1.age = 21; s2.name = "Gargi"; s2.age = 13; printf("\nName: %s \n Age: %d ",s1.name,s1.age); printf("\nName: %s \n Age: %d ",s2.name,s2.age); }
20th Jun 2023, 12:45 AM
Bob_Li
Bob_Li - avatar
+ 1
A char array can (and indeed must) be used to store strings, but you can't naively assign strings to an array with =, any more than you could do that with an array of numbers. You either need to assign it char-by-char yourself, or like Codenath shows, #include string.h and let strcpy() do that work for you behind the scenes.
19th Jun 2023, 7:59 PM
Orin Cook
Orin Cook - avatar