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

如何不使用指针与malloc实现栈上结构体创建及非指针传参?

修改后的无动态内存分配版C程序

针对你的需求,直接在栈上创建结构体、用指针模拟引用传递(C语言没有原生引用)的修改方案如下:

核心修改点

  • 栈上创建结构体:直接定义结构体变量,无需malloc或alloca(alloca是栈上动态分配,没必要,直接定义变量更简单)
  • 结构体传递:用指针传递模拟“引用传递”,既可以避免拷贝结构体,又能在函数内修改结构体内容
  • 移除动态内存操作:把Person结构体的name字段改成固定长度的字符数组,彻底摆脱malloc/free和strdup

修改后的代码

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

// 修改结构体:用固定字符数组存名字,避免动态分配
#define NAME_MAX_LEN 50
struct Person {
    char name[NAME_MAX_LEN];
    int age;
    int height;
    int weight;
};

// 打印结构体:用指针传递(模拟引用传递),避免拷贝
void Person_print(const struct Person *who)
{
    printf("Name : %s\n", who->name);
    printf("\tAge: %d\n", who->age);
    printf("\theight: %d\n", who->height);
    printf("\tweight: %d\n", who->weight);
}

// 修改结构体属性的函数:同样用指针传递,直接修改原结构体
void Person_age_up(struct Person *who, int years)
{
    who->age += years;
}

void Person_adjust_weight(struct Person *who, int delta)
{
    who->weight += delta;
}

void Person_adjust_height(struct Person *who, int delta)
{
    who->height += delta;
}

int main(int argc, char* argv[])
{
    // 直接在栈上创建并初始化结构体
    struct Person joe = {"Joe Alex", 32, 64, 140};
    struct Person frank = {"Frank Blank", 20, 72, 180};

    // 打印结构体及其内存地址
    printf("Joe is at memory location %p:\n", &joe);
    Person_print(&joe);

    printf("Frank is at memory location %p:\n", &frank);
    Person_print(&frank);

    // 修改结构体属性
    Person_age_up(&joe, 20);
    Person_adjust_height(&joe, -2);
    Person_adjust_weight(&joe, 40);
    Person_print(&joe);

    Person_age_up(&frank, 20);
    Person_adjust_weight(&frank, 20);
    Person_print(&frank);

    // 栈上变量会在函数结束时自动释放,无需手动销毁
    return 0;
}

关键说明

  1. 栈上结构体创建:直接定义struct Person joe = {...};,变量joe会在栈上分配,函数执行完毕后自动释放,完全不需要malloc或alloca。
  2. 引用传递的实现:C语言没有原生的引用类型,所以用指针传递来模拟——把结构体的地址传给函数,函数通过指针直接操作原结构体,避免值传递的拷贝开销,也能修改原结构体的内容。
  3. 移除动态内存:把char *name改成char name[NAME_MAX_LEN],初始化时直接拷贝字符串,不需要strdup(内部用malloc),也就不需要手动释放内存。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:28:12