c语言动态结构体数组问题

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

// 课程信息
typedef struct {
    long id; // 课程编号
    char *name; // 课程名称
    int type; // 课程性质
    int hours; // 学时
    int teaching_hours; // 授课学时
    int experiment_or_machine_hours; // 实验或上机学时
    float credit; // 学分
    int semester; // 开课学期
} course;

// 通过学分查询课程
void queryByCredit() {
    float credit;
    int flag, len = 0;
    course *matching_courses = (course *) malloc(sizeof(course));
    printf("%ld", sizeof(course));

    FILE *fp = getFile("../course_info.txt", "r");
    // 初始化课程信息结构体
    course course_temp;
    course_temp.name = (char *) malloc(100 * sizeof(char));

    while (1) {
        printf("请输入学分: ");
        scanf("%f", &credit);

        while (!feof(fp)) {
            // 读取新的课程信息
            readCourseInfo(fp, &course_temp);

            // 学分匹配
            // 由于学分为浮点型小数, 因此比较时不能准确比较, 因此当小于某小数时则成立
            if (fabsf(course_temp.credit - credit) < 0.01) {
                // matching_courses[len++] = course_temp;
                *(matching_courses + sizeof(course_temp) * len++) = course_temp;
                matching_courses = (course *) realloc(matching_courses, sizeof(course));
            }
        }

        // 打印表格
        showLine();
        showCourseInfoHeader();
        for (int i = 0; i < len; ++i) {
            printCourseInfo(*(matching_courses + 40 * i));
        }
        showLine();

        flag = isContinue();
        if (flag == BACK)
            break;
    }
}

在我的系统(ubuntu 18.04)中
为什么这里matching_courses[len++]的地址每次都只增加28,而实际上他应该加40才是正确的

阅读 2.5k
1 个回答

0x28 == 40

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进