日志15

在 C++ 中,结构体指针 是指向结构体的指针,用于操作结构体类型的数据。以下是关于结构体指针的一些基本知识:

1. 定义结构体

首先,需要定义一个结构体:

#include <iostream>
using namespace std;

struct Student {
    int id;
    string name;
    double score;
};

2. 创建结构体指针

创建结构体变量和结构体指针的方式如下:

(1)直接指向结构体变量:

Student s1 = {1, "Alice", 90.5}; // 定义结构体变量
Student* p = &s1;               // 指针指向结构体变量

// 使用结构体指针访问成员
cout << "ID: " << p->id << endl;
cout << "Name: " << p->name << endl;
cout << "Score: " << p->score << endl;

注意

  • p->id 等价于 (*p).id,使用 -> 运算符更加简洁。

(2)动态分配内存:

使用 new 关键字动态创建结构体变量:

Student* p = new Student; // 动态分配内存
p->id = 2;
p->name = "Bob";
p->score = 88.0;

cout << "ID: " << p->id << endl;
cout << "Name: " << p->name << endl;
cout << "Score: " << p->score << endl;

delete p; // 释放内存

3. 结构体指针数组

如果需要存储多个结构体指针,可以使用结构体指针数组:

Student s1 = {1, "Alice", 90.5};
Student s2 = {2, "Bob", 88.0};

Student* students[2] = {&s1, &s2};

for (int i = 0; i < 2; ++i) {
    cout << "ID: " << students[i]->id << endl;
    cout << "Name: " << students[i]->name << endl;
    cout << "Score: " << students[i]->score << endl;
}

4. 传递结构体指针给函数

通过指针传递结构体到函数,可以避免拷贝大数据,提升性能:

void printStudent(const Student* p) {
    cout << "ID: " << p->id << endl;
    cout << "Name: " << p->name << endl;
    cout << "Score: " << p->score << endl;
}

int main() {
    Student s1 = {1, "Alice", 90.5};
    printStudent(&s1); // 传递指针
    return 0;
}

小结

  • 使用结构体指针可以更高效地访问结构体成员。
  • 动态分配的结构体变量需要及时释放内存(delete)。
  • 通过指针传递结构体数据给函数,能够减少数据拷贝
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务