c语言

c语言结构体指针赋值的方法是什么

小亿
384
2023-12-14 01:52:30
栏目: 编程语言
C语言开发专用服务器,限时0元免费领! 查看>>

在C语言中,结构体指针赋值有两种方法:

  1. 使用"->"操作符:通过结构体指针访问结构体成员并赋值。例如:
struct Student {
    int id;
    char name[20];
};

int main() {
    struct Student s1;
    struct Student *ptr_s1 = &s1;
    
    ptr_s1->id = 1;
    strcpy(ptr_s1->name, "John");
    
    return 0;
}
  1. 使用"*"操作符:通过解引用结构体指针访问结构体成员并赋值。例如:
struct Student {
    int id;
    char name[20];
};

int main() {
    struct Student s1;
    struct Student *ptr_s1 = &s1;
    
    (*ptr_s1).id = 1;
    strcpy((*ptr_s1).name, "John");
    
    return 0;
}

这两种方法都可以对结构体指针所指向的结构体成员进行赋值操作。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:c语言结构体函数指针如何赋值

0
看了该问题的人还看了