/*************************************** **************************************** ** Program name: dynamic Array ** program function: C language dynamic array, object-oriented implementation method ** upgrade Description: all methods use this pointer to operate objects; size maintenance is also put in the method ** program Author: syrchina ** modification date: 2012-3-12 *************************************** **************************************** /# include <stdio. h> # include <stdlib. h> typedef int mytype; typedef struct _ darray {mytype * ele; int size; void (* init) (struct _ Darr Ay * da_this); void (* setlen) (struct _ darray * da_this, int newsize); void (* destory) (struct _ darray * da_this);} darray, * pdarray; void init_darray (pdarray da_this) {If (null = (da_this-> ele = (mytype *) calloc (da_this-> size, sizeof (mytype )))) {printf ("init failed, Program terminated! "); While (1) ;}} void changesize_darray (pdarray da_this, int newsize) {If (null = (da_this-> ele = (mytype *) realloc (da_this-> ele, newsize * sizeof (mytype) {printf ("changesize failed, Program terminated! "); While (1);} da_this-> size = newsize;} void destory_darray (pdarray da_this) {free (da_this-> Ele); da_this-> ele = NULL ;} int main (INT argc, char * argv []) {int I = 0; darray A = {null, 10, init_darray, changesize_darray, destory_darray};. init (& A); // dynamic array initialization for (I = 0; I <. size; I ++) {. ele [I] = I;}. setlen (& A, 20); // change the length of the dynamic array for (I = 10; I <. size; I ++) {. ele [I] = I;} for (I = 0; I <. size; I ++) // read {printf ("% d",. ele [I]);}. destory (& A); // destroy return 0 ;}
When applying for memory failure, we do not recommend using while (1); The above is just an example.