You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中如何在函数内引用结构体数组中的特定结构体?代码调试求助

C语言代码修复与结构体数组引用问题解答

一、修复代码让两个printf正常输出

你的代码会崩溃导致第二个printf无法执行,核心问题是main里的test指针未初始化就传给了pass1,pass1中直接访问arr[pos]属于操作野指针,触发内存错误。修复后的代码如下:

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

struct obj_t {
    int id;
    float x;
    float y;
};

struct cluster_t {
    int size;
    int capacity;
    struct obj_t *obj;
};

void obj_ctor(struct obj_t *p, struct obj_t obj) {
    p->id = obj.id;
    p->x = obj.x;
    p->y = obj.y;
}

void pass(struct cluster_t *p, struct obj_t add) {
    // 增加容量检查,避免越界写入
    if (p->size < p->capacity) {
        obj_ctor(&p->obj[p->size], add);
        p->size += 1;
    }
}

void pass1(struct cluster_t **arr) {
    struct obj_t o3 = {1, 2.0f, 3.0f};
    int count = 20;
    int pos = 0;
    // 先给每个cluster分配内存,避免野指针访问
    while (pos < 3) {
        arr[pos] = malloc(sizeof(struct cluster_t));
        arr[pos]->capacity = 3;
        arr[pos]->size = 0;
        arr[pos]->obj = malloc(count * sizeof(struct obj_t));
        pass(arr[pos], o3);
        pos++;
    }
}

int main(int argc, char *argv[]) {
    printf("Testing\n");
    // 声明存放3个cluster指针的数组
    struct cluster_t *test[3];
    pass1(test);
    printf("GOT HERE\n");

    // 释放内存,避免内存泄漏
    for (int i = 0; i < 3; i++) {
        free(test[i]->obj);
        free(test[i]);
    }
    return 0;
}

关键修复点:

  • main中改用struct cluster_t *test[3],这是一个可容纳3个cluster_t指针的数组,避免野指针问题
  • pass1中先给每个arr[pos]分配cluster_t结构体的内存,再初始化成员
  • 给printf添加\n,确保输出立即刷新到终端(避免因缓冲区问题看不到内容)
  • 新增内存释放逻辑,防止内存泄漏
  • pass函数中增加容量检查,避免数组越界写入

二、函数内引用结构体数组中的特定结构体

根据数组类型的不同,访问方式略有区别:

1. 直接使用结构体数组

如果定义的是struct cluster_t clusters[5];(栈上直接分配的结构体数组),函数中可这样访问:

// 获取第i个cluster_t结构体的指针
struct cluster_t *curr_cluster = &clusters[i];
// 获取该cluster中第j个obj_t结构体的指针
struct obj_t *curr_obj = &clusters[i].obj[j];

// 修改成员示例
curr_cluster->size = 2;
curr_obj->x = 4.0f;

2. 使用结构体指针数组(如你代码中的struct cluster_t **arr)

如果传入的是指向指针数组的指针(比如pass1的参数),访问第i个cluster里第j个obj的方式:

// 获取第i个cluster_t的指针
struct cluster_t *curr_cluster = arr[i];
// 获取第i个cluster里第j个obj_t的指针
struct obj_t *curr_obj = &arr[i]->obj[j];

// 直接访问成员示例
printf("Cluster %d size: %d\n", i, arr[i]->size);
printf("Obj %d ID: %d\n", j, arr[i]->obj[j].id);

3. 单个结构体指针

如果是单个struct cluster_t *p,访问它的obj数组元素:

// 获取第j个obj_t的指针
struct obj_t *curr_obj = &p->obj[j];
// 直接访问成员
printf("Obj X coordinate: %.1f\n", p->obj[j].x);

内容的提问来源于stack exchange,提问作者Frederik Tóth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:31:03