[英]Assigning values and passing struct as parameter
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 ? 为什么说到char我不能简单地使用'='来赋值?
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. 我如何将在main(){}中初始化的结构作为参数传递给函数,并在函数中更改其值而无需返回。 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 ? 这是正确的方法吗?
No matter which way you pass the struct (by value or by pointer), you cannot directly assign a string literal to a char array. 无论采用哪种方式传递结构(通过值或指针),都不能直接将字符串文字分配给char数组。 You can only use strcpy or strncpy or something else that copies the characters one by one.
您只能使用strcpy或strncpy或其他一种逐个复制字符的方式。
But there is a workaround, you can directly assign struct to another one. 但是有一种解决方法,您可以将struct直接分配给另一个。 C compiler will perform a bitwise copy of the struct.
C编译器将执行该结构的按位复制。
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: 附上一个使用指针传递struct的示例:
void handle_student(struct student *p) { ... }
int main() {
struct student s1;
handle_student(&s1);
}
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" };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.