分配值并将struct作为参数传递

时间:2014-10-24 03:43:41

标签: c struct parameters

  • 要将 char值分配到struct'字段',我必须使用 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);
       }
    

这是正确的方法吗?

2 个答案:

答案 0 :(得分:1)

无论您通过哪种方式传递结构(按值或通过指针),都无法直接将字符串文字指定给char数组。您只能使用strcpy或strncpy或其他可以逐个复制字符的内容。

但是有一种解决方法,你可以直接将struct分配给另一个。 C编译器将执行struct的按位复制。

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);
}

答案 1 :(得分:1)

这只是一个附加信息

在声明结构变量时,可以将其初始化为如下所示。

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

}
相关问题