Dynamic Array in C Language (in an object-oriented programming style)

Source: Internet
Author: User
/*************************************** **************************************** ** 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.