c语言 结构体
c语言 结构体
在C语言中,结构体(struct)是一种复合数据类型,它可以存储不同类型的数据项。结构体中可以定义多个不同的成员(member),每个成员可以是基本数据类型或其他复合类型。
以下是一些使用C语言结构体的常见方法:
- 
定义和使用结构体 
struct Student {
    char name[50];
    int age;
    float score;
};
int main() {
    struct Student stu;  // 声明结构体变量
    strcpy(stu.name, "John");
    stu.age = 20;
    stu.score = 88.5;
    printf("Name: %s\n", stu.name);
    printf("Age: %d\n", stu.age);
    printf("Score: %.1f\n", stu.score);
    return 0;
}
- 
使用指针访问结构体成员 
struct Student {
    char name[50];
    int age;
    float score;
};
int main() {
    struct Student stu;
    struct Student *pStu = &stu;
    strcpy(pStu->name, "John");
    pStu->age = 20;
    pStu->score = 88.5;
    printf("Name: %s\n", pStu->name);
    printf("Age: %d\n", pStu->age);
    printf("Score: %.1f\n", pStu->score);
    return 0;
}
- 
定义结构体数组 
struct Student {
    char name[50];
    int age;
    float score;
};
int main() {
    struct Student students[5];
    for (int i = 0; i < 5; i++) {
        printf("Student %d: ", i + 1);
        scanf("%s %d %f", students[i].name, &students[i].age, &students[i].score);
    }
    return 0;
}
- 
定义结构体指针数组 
struct Student {
    char name[50];
    int age;
    float score;
};
int main() {
    struct Student *students[5];
    for (int i = 0; i < 5; i++) {
        students[i] = (struct Student *)malloc(sizeof(struct Student));
        printf("Student %d: ", i + 1);
        scanf("%s %d %f", students[i]->name, &students[i]->age, &students[i]->score);
    }
    for (int i = 0; i < 5; i++) {
        printf("Name: %s\n", students[i]->name);
        printf("Age: %d\n", students[i]->age);
        printf("Score: %.1f\n", students[i]->score);
        free(students[i]);
    }
    return 0;
}
- 
定义结构体时声明位域 
struct Student {
    unsigned int score : 5;
    unsigned int age : 3;
    char name[4];
};
int main() {
    struct Student stu;
    stu.score = 88;
    stu.age = 20;
    strcpy(stu.name, "John");
    printf("Name: %s\n", stu.name);
    printf("Age: %d\n", stu.age);
    printf("Score: %d\n", stu.score);
    return 0;
}
- 
使用typedef定义结构体别名 
typedef struct Student {
    char name[50];
    int age;
    float score;
} Student;
int main() {
提示:AI自动生成,仅供参考
    漫思
 
                    
                     
                    
                 
                    
                 
                
            
         
 
         浙公网安备 33010602011771号
浙公网安备 33010602011771号