allocate.c

本文介绍了一个用于种群和个体的数据结构内存分配与释放的方法。包括为种群分配内存、为个体分配内存、释放种群内存和释放个体内存的函数实现。涉及的变量包括实数变量、二进制变量、目标函数值和约束条件等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* Memory allocation and deallocation routines */

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

# include "global.h"
# include "rand.h"

/* Function to allocate memory to a population */
void allocate_memory_pop (population *pop, int size)
{
    int i;
    pop->ind = (individual *)malloc(size*sizeof(individual));
    for (i=0; i<size; i++)
    {
        allocate_memory_ind (&(pop->ind[i]));
    }
    return;
}

/* Function to allocate memory to an individual */
void allocate_memory_ind (individual *ind)
{
    int j;
    if (nreal != 0)//nreal is a global variable,is the number of "real variables"
    {
        ind->xreal = (double *)malloc(nreal*sizeof(double));
    }
    if (nbin != 0)//nbin is a global variable, is the number of "binary variables"
    {
        ind->xbin = (double *)malloc(nbin*sizeof(double));
        ind->gene = (int **)malloc(nbin*sizeof(int *));
        for (j=0; j<nbin; j++)
        {
            ind->gene[j] = (int *)malloc(nbits[j]*sizeof(int));//nbits is an arrary of "nbin*(double)",and nbits[j] is initialized in main func(nsga2r.c)
        }
    }
    ind->obj = (double *)malloc(nobj*sizeof(double));//nobj is a global variable, is the number of objectives
    if (ncon != 0)
    {
        ind->constr = (double *)malloc(ncon*sizeof(double));//ncon is a global variable, is the number of constraints
    }
    return;
}

/* Function to deallocate memory to a population */
void deallocate_memory_pop (population *pop, int size)
{
    int i;
    for (i=0; i<size; i++)
    {
        deallocate_memory_ind (&(pop->ind[i]));
    }
    free (pop->ind);
    return;
}

/* Function to deallocate memory to an individual */
void deallocate_memory_ind (individual *ind)
{
    int j;
    if (nreal != 0)
    {
        free(ind->xreal);
    }
    if (nbin != 0)
    {
        for (j=0; j<nbin; j++)
        {
            free(ind->gene[j]);
        }
        free(ind->xbin);
        free(ind->gene);
    }
    free(ind->obj);
    if (ncon != 0)
    {
        free(ind->constr);
    }
    return;
}

源代码来源:http://www.iitk.ac.in/kangal/codes.shtml

中间添加了一些自己的注释,用下划线标识的。

(其实就是一些可以用SI查找一下啊就能找到这些变量的含义。只是希望记下来印象深刻一些吧。)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值