0
  • To asign a char value into the struct 'field', I have to use strcpy ?

I tried this:

struct student{ char name[50]; int age; }; int main(){ struct student std; std.name = "john"; //Doesnt work strcpy(std.name, "john"); //It DOES work std.age = 20; return 0;} 

Why when comes to char I can not simply use the ' = ' to assign a value ?

  • How may I pass a struct initialized in main(){} as a parameter to a function and change it's values inside the function without the need of a return. Do I just use the '*' like:

     void MyFunction(struct student *std){ std->Name = "John"; std->Age = 20; } int main(){ struct student me; Myfunction(me); } 

Is that the correct way to do so ?

2 Answers 2

1

No matter which way you pass the struct (by value or by pointer), you cannot directly assign a string literal to a char array. You can only use strcpy or strncpy or something else that copies the characters one by one.

But there is a workaround, you can directly assign struct to another one. C compiler will perform a bitwise copy of the struct.

struct student s1; strcpy(s1.name, "john"); s1.age = 10; struct student s2; s2 = s1; // now s2 is exactly same as s1. 

Attach an example of use pointer to pass struct:

void handle_student(struct student *p) { ... } int main() { struct student s1; handle_student(&s1); } 
Sign up to request clarification or add additional context in comments.

1 Comment

better to use strncpy(s1.name, "john", sizeof s1.name); so buffer size is warranted not to overflow.
1

This is just an additional information

While declaring the structure variable, it can be initialized as below.

int main(){ struct student s1 = {"John", 21}; //or struct student s = {.name= "John" }; } 

1 Comment

You cannot use that in older ansi-c compilers for automatic variables like the ones you have used in your example. Even, the .name notation is only allowed in newer ansi-c compilers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.