C語言實現動態數組

來源:互聯網
上載者:User

現正在做一個項目,要使用動態數組,本想在網站上找一個代碼,由於這個項目比較急,本想在網站上找個現成的代碼直接用,可是找來找到,就覺得adm_qxx兄寫的還算規則,可後來發現動態數組最重要的動態擴充部分竟然沒有實現,所以我就修改了adm_qxx的代碼,並貼在下面。

#include <stdio.h>#include <stdlib.h>#include <string.h>#define INIT_DATA_NUM 10#define FALSE 0#define TRUE 1typedef 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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.