C语言实现动态数组

现正在做一个项目,要使用动态数组,本想在网站上找一个代码,由于这个项目比较急,本想在网站上找个现成的代码直接用,可是找来找到,就觉得adm_qxx兄写的还算规则,可后来发现动态数组最重要的动态扩展部分竟然没有实现,所以我就修改了adm_qxx的代码,并贴在下面。

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


#define INIT_DATA_NUM 10
#define FALSE 0
#define TRUE 1


typedef unsigned char     BOOL;
typedef int elem_t;
typedef struct
{
    int           iCount;
    int           iCapacity;
    elem_t  * pData;
}Array_t;


BOOL initArray( Array_t * array, int size );
BOOL setValue( Array_t * array, int index, elem_t val );
BOOL extArray(Array_t *array, int size);
elem_t * getRef( Array_t * array, int index );
elem_t getValue( Array_t * array, int index );
BOOL destroyArray( Array_t * array );




BOOL initArray(Array_t * array, int size)
{
    BOOL bRet = FALSE;
    int initSize = (size > 0) ? size : INIT_DATA_NUM;


    array->pData = (elem_t *)malloc(initSize * sizeof( elem_t));
    if (array->pData != NULL)
    {
        array->iCapacity = initSize;
        array->iCount = 0;
        bRet = TRUE;
    }
    return bRet;
}


BOOL extArray(Array_t *array, int size)
{
    BOOL bRet = FALSE;
    int extSize = (size > 0) ? size : INIT_DATA_NUM;
    array->pData = (elem_t *)realloc(array->pData, (extSize + arrar->iCount) * sizeof(elem_t));
    if (array->pData != NULL)
    {
        array->iCapacity += extSize;
        bRet = TRUE;
    }
    return bRet;
}


BOOL setValue(Array_t *array, int index, elem_t val)
{
    BOOL bRet = FALSE;
    if(index >= 0 && index < array->iCapacity)
    {
        array->pData[index] = val;
        array->iCount++;
        bRet = TRUE;
    }
    else if (index >= array->iCapacity)
    {
        if (extArray(array, 0))
        {
            array->pData[index] = val;
            array->iCount++;
            bRet = TRUE;
        }
    }
    return bRet;
}


elem_t *getRef( Array_t *array, int index )
{
    elem_t * eRet = NULL;
    if( index > 0 && index < array->iCount )
    {
        eRet = array->pData + index;
    }
    return eRet;
}


elem_t getValue( Array_t * array, int index )
{
    return array->pData[index];
}


int getCount(Array_t *array)
{
    return array->iCount;
}


BOOL destroyArray( Array_t * array )
{
    free( array->pData );
    array->pData = NULL;
    return TRUE;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张无印

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值