Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-07-09) 阅读数 11 #程序编程
文章标签 c语言

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

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

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门