- 要将char 值 分配到结构“字段”中,我必须 使用strcpy 吗?
我试过这个:
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;}
为什么在谈到 char 时我不能简单地使用“=”来赋值?
我如何将在 main(){} 中初始化的结构作为参数传递给函数,并在函数内部更改它的值而不需要返回。 我是否只使用像这样的“*”:
void MyFunction(struct student *std){ std->Name = "John"; std->Age = 20; } int main(){ struct student me; Myfunction(me); }
这是这样做的正确方法吗?
最佳答案
无论以哪种方式传递结构(按值或按指针),都不能直接将字符串文字分配给 char 数组。您只能使用 strcpy 或 strncpy 或其他可以逐个复制字符的东西。
但是有一个解决方法,你可以直接将struct赋值给另一个struct。 C 编译器将执行结构的按位复制。
struct student s1;
strcpy(s1.name, "john");
s1.age = 10;
struct student s2;
s2 = s1; // now s2 is exactly same as s1.
附上使用指针传递struct的例子:
void handle_student(struct student *p) { ... }
int main() {
struct student s1;
handle_student(&s1);
}
关于c - 分配值并将结构作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26541141/