lihuayuli 2025-05-08 23:39 采纳率: 100%
浏览 74
已结题

C语言提示提示passing argument 1 of 'fprintf' from incompatible pointer type [-Wincompatible-pointer-types]怎么办?

问题遇到的现象和发生背景

环境里面提示代码错误:

img


在保存文件那一行提示passing argument 1 of 'fprintf' from incompatible pointer type [-Wincompatible-pointer-types]

用代码块功能插入代码,请勿粘贴截图。 不用代码块回答率下降 50%
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glpk.h>

#define MAX_LINE_LEN 1024

typedef struct
{
    int year;
    char securities_code[20];
    double financial_expense;
    double dividend;
    double operating_cost;
    double total_asset;
    double employee;
    double total_profit;
    double operating_income;
    double non_current_liabilities;
    double paid_in_capital;
} DMU;

DMU *read_csv(const char *filename, int *count)
{
    FILE *fp = fopen(filename, "r");
    if (!fp)
    {
        perror("Error opening file");
        return NULL;
    }

    DMU *data = NULL;
    char line[MAX_LINE_LEN];
    *count = 0;

    // 跳过 UTF-8 BOM
    if (fgetc(fp) == 0xEF && fgetc(fp) == 0xBB && fgetc(fp) == 0xBF)
    {
        // BOM 已检测
    }
    else
    {
        rewind(fp);
    }

    // 跳过标题行
    fgets(line, sizeof(line), fp);

    while (fgets(line, sizeof(line), fp))
    {
        DMU *temp = realloc(data, (*count + 1) * sizeof(DMU));
        if (!temp)
        {
            free(data);
            fclose(fp);
            return NULL;
        }
        data = temp;

        DMU *d = &data[*count];
        memset(d, 0, sizeof(DMU));

        char *token;
        int field = 0;       // 定义一次
        int max_fields = 11; // 总字段数

        token = strtok(line, ",");
        while (token != NULL && field < max_fields)
        {
            switch (field)
            {
            case 0:
                d->year = atoi(token);
                printf("Parsing field %d: year = %d\n", field, d->year);
                break;
            case 1:
                strncpy(d->securities_code, token, sizeof(d->securities_code) - 1);
                d->securities_code[sizeof(d->securities_code) - 1] = '\0'; // 确保终止
                break;
            case 2:
                d->financial_expense = atof(token);
                break;
            case 3:
                d->dividend = atof(token);
                break;
            case 4:
                d->operating_cost = atof(token);
                break;
            case 5:
                d->total_asset = atof(token);
                break;
            case 6:
                d->employee = atof(token);
                break;
            case 7:
                d->total_profit = atof(token);
                break;
            case 8:
                d->operating_income = atof(token);
                break;
            case 9:
                d->non_current_liabilities = atof(token);
                break;
            case 10:
                d->paid_in_capital = atof(token);
                break;
            default:
                break;
            }
            token = strtok(NULL, ",");
            field++;
        }

        // 检查字段数量
        if (field != max_fields)
        {
            fprintf(stderr, "Error: Line %d has %d fields (expected 11).\n", *count + 1, field);
            free(data);
            fclose(fp);
            return NULL;
        }

        (*count)++;
    }

    fclose(fp);
    return data;
}

double calculate_efficiency(DMU *dmus, int num_dmus, int target_idx)
{
    DMU *target = &dmus[target_idx];
    glp_prob *lp = glp_create_prob();
    glp_set_obj_dir(lp, GLP_MAX);

    // ================== Add Variables ==================
    glp_add_cols(lp, 7); // 列索引1-7
    for (int i = 1; i <= 7; i++)
    {
        glp_set_col_bnds(lp, i, GLP_LO, 0.0, 0.0);
    }

    // ================== Objective Function ==================
    glp_set_obj_coef(lp, 6, target->operating_income); // u0 (第6列)
    glp_set_obj_coef(lp, 7, target->total_profit);     // u1 (第7列)

    // ================== Constraints ==================
    int row_count = 0;

    // 约束1: 标准化输入
    row_count++;
    glp_add_rows(lp, 1);
    glp_set_row_bnds(lp, row_count, GLP_FX, 0.5, 0.5);
    {
        int ind[] = {0, 1, 2};
        double val[] = {
            0.0,
            target->financial_expense,
            target->dividend,
        };
        for (int k = 1; k <= 2; k++)
        {
            printf("  ind[%d]=%d, val=%.2f\n", k, ind[k], val[k]);
        }
        printf("\n");
        glp_set_mat_row(lp, row_count, 2, ind, val);
    }
    // 约束1: 标准化输入
    row_count++;
    glp_add_rows(lp, 1);
    glp_set_row_bnds(lp, row_count, GLP_FX, 0.5, 0.5);
    {
        int ind[] = {0, 1, 2, 3};
        double val[] = {
            0.0,
            target->operating_cost,
            target->total_asset,
            target->employee,
        };
        printf("Setting row %d, ind[] = ", row_count);

        printf("Setting constraint1 row %d with %d elements:\n", row_count, 5);
        printf("\n");
        glp_set_mat_row(lp, row_count, 3, ind, val);
    }

    // 约束2: 所有DMU的约束
    for (int j = 0; j < num_dmus; j++)
    {
        DMU *dmu = &dmus[j];
        row_count++;
        glp_add_rows(lp, 1);
        glp_set_row_bnds(lp, row_count, GLP_LO, 0.0, 0.0);

        int ind[] = {0, 1, 2, 3, 4}; // 必须包含7个合法索引
        double val[] = {0.0, dmu->financial_expense,
                        dmu->dividend,
                        -dmu->non_current_liabilities,
                        -dmu->paid_in_capital};
        // 打印调试信息
        printf("Setting DMU %d constraint (row %d): ind[] = ", j, row_count);
        // 检查索引合法性
        for (int k = 1; k <= 4; k++)
        {
            if (ind[k] < 1 || ind[k] > 4)
            {
                fprintf(stderr, "Invalid column index %d at row %d\n", ind[k], row_count);
                printf("  ind[%d] = %d, val[%d] = %f\n", k, ind[k], k, val[k]);
                exit(1);
            }
        }

        glp_set_mat_row(lp, row_count, 4, ind, val);
    }
    for (int j = 0; j < num_dmus; j++)
    {
        DMU *dmu = &dmus[j];
        row_count++;
        glp_add_rows(lp, 1);
        glp_set_row_bnds(lp, row_count, GLP_LO, 0.0, 0.0);

        int ind[] = {0, 1, 2, 3, 4, 5, 6, 7}; // 必须包含7个合法索引
        double val[] = {0.0,
                        dmu->operating_cost,
                        dmu->total_asset,
                        dmu->employee,
                        dmu->non_current_liabilities,
                        dmu->paid_in_capital,
                        -dmu->operating_income,
                        -dmu->total_profit};
        // 打印调试信息
        printf("Setting DMU %d constraint (row %d): ind[] = ", j, row_count);
        // 检查索引合法性
        for (int k = 1; k <= 7; k++)
        {
            printf("  ind[%d]=%d, val=%.2f\n", k, ind[k], val[k]);
            if (ind[k] < 1 || ind[k] > 7)
            {
                fprintf(stderr, "Invalid column index %d at row %d\n", ind[k], row_count);
                printf("  ind[%d] = %d, val[%d] = %f\n", k, ind[k], k, val[k]);
                exit(1);
            }
        }

        glp_set_mat_row(lp, row_count, 7, ind, val);
    }

    // ================== 求解 ==================
    glp_simplex(lp, NULL);
    double eff = glp_get_obj_val(lp);
    glp_delete_prob(lp);
    return eff;
}
int main()
{
    int num_dmus;
    DMU *dmus = read_csv("./test.csv", &num_dmus);
    if (!dmus)
        return 1;

    for (int i = 0; i < num_dmus; i++)
    {
        double eff = calculate_efficiency(dmus, num_dmus, i);
        printf("DMU %s (%d): Efficiency = %.4f\n",
               dmus[i].securities_code, dmus[i].year, eff);
        FILE *fp = fopen("output.csv", "a");
        if (fp == NULL)
        {
            printf("文件打开失败\n");
            return 1;
        }

        // 追加日志内容
        fprintf(fp, "DMU %s (%d): Efficiency = %.4f\n",
                dmus[i].securities_code, dmus[i].year, eff);
        fclose(fp);
    }

    free(dmus);
    return 0;
}

运行结果及详细报错内容
我的解答思路和尝试过的方法,不写自己思路的,回答率下降 60%

没什么思路,感觉参数写得没问题

我想要达到的结果,如果你需要快速回答,请尝试 “付费悬赏”
  • 写回答

5条回答 默认 最新

  • 宝码香车 优质创作者: JavaScript技术领域 2025-05-08 23:43
    关注

    让【宝码香车】来帮你解答,本回答参考DeepSeek编写,并整理提供。
    如果还有疑问可以点击头像关注私信或评论。如果答案让您满意,请采纳、点赞、关注,非常感谢!

    这个错误是因为fprintf函数的第一个参数需要是FILE*类型,但编译器检测到可能传递了不兼容的指针类型。根据你的代码,问题可能出在文件指针fp的使用上。

    解决方案

    1. 检查文件指针是否正确打开
      确保fopen成功打开文件并返回有效的FILE*指针。你的代码中已经做了检查,这是正确的。

    2. 确保fprintf参数类型正确
      你的fprintf调用看起来是正确的,但编译器可能误报了类型不匹配。可以尝试以下修改:

    FILE *fp = fopen("output.csv", "a");
    if (fp == NULL) {
        printf("文件打开失败\n");
        return 1;
    }
    
    // 明确转换fp为FILE*类型(虽然通常不需要)
    fprintf((FILE*)fp, "DMU %s (%d): Efficiency = %.4f\n",
            dmus[i].securities_code, dmus[i].year, eff);
    fclose(fp);
    
    1. 检查编译器设置
      这个警告可能是编译器过于严格导致的。可以尝试:

      • 更新编译器版本
      • 添加编译选项-Wno-incompatible-pointer-types来禁用这个特定警告
    2. 完整修复代码
      以下是修改后的完整代码片段:

    for (int i = 0; i < num_dmus; i++) {
        double eff = calculate_efficiency(dmus, num_dmus, i);
        printf("DMU %s (%d): Efficiency = %.4f\n",
               dmus[i].securities_code, dmus[i].year, eff);
        
        FILE *fp = fopen("output.csv", "a");
        if (fp == NULL) {
            perror("无法打开output.csv");
            return 1;
        }
        
        // 确保所有参数类型正确
        fprintf(fp, "DMU %s (%d): Efficiency = %.4f\n",
                dmus[i].securities_code, dmus[i].year, eff);
        fclose(fp);
    }
    

    其他建议

    1. 错误处理改进
      使用perror代替printf来显示文件打开错误,这样能显示更详细的错误信息。

    2. 文件打开模式
      考虑使用"w"模式而不是"a",除非你确实需要追加内容。

    3. 检查结构体成员
      确保dmus[i].securities_codedmus[i].year的类型与格式说明符%s%d匹配。

    如果问题仍然存在,可能需要检查编译器版本或提供更完整的错误信息。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 5月12日
  • 已采纳回答 5月10日
  • 创建了问题 5月8日