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

C语言中如何返回struct outter内目标struct inner元素的地址

C 语言结构体数组成员地址返回方法

核心实现逻辑

你已经找到目标元素对应的数组下标后,直接取该下标元素的地址返回即可,示例代码如下:

struct inner{
 int foo;
};

struct outter{
 struct inner innerStruct[100];
};

// 这里假设struct outter实例为全局变量,你也可以根据需求调整为参数传入
struct outter global_outter;

struct inner * foo1(int target){
    // 此处省略查找target的逻辑,假设最终得到的有效数组下标为found_idx,取值范围0~99
    int found_idx = /* 你的查找结果 */;

    // 直接返回目标元素的地址
    return &global_outter.innerStruct[found_idx];
}

补充说明

  • 如果不想使用全局变量存储struct outter实例,可以修改函数原型,将实例指针作为参数传入:
    struct inner * foo1(struct outter *outter_p, int target){
        int found_idx = /* 你的查找结果 */;
        return &outter_p->innerStruct[found_idx];
    }
    
  • 注意要保证拿到的下标found_idx在0到99的合法范围内,避免返回越界的非法地址

内容的提问来源于stack exchange,提问作者python_newbie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:15:05