c - 分配值并将结构作为参数传递

标签 c struct parameters

  • 要将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/

相关文章:

java - 在一个变量中引用方法的参数

java - java中如何将一个类中创建的对象传递给另一个类?

Java - 将对象的 ArrayList 传递给使用对象实现的接口(interface)的 ArrayList 的函数

c - 字符串指针,统计单词中的字母数量

c - C语言中存在类型删除的概念吗?

c - 为什么下面的代码不打印整数的二进制表示形式?

c - 将位图图像写入文件

swift - 通过函数传递时不能修改对象数组?

对如何添加到另一个结构中的链表结构感到困惑

c - 指针使用不正确导致输出错误?