#include <stdio.h> #include <stdlib.h> #include <memory.h> #define datatype int struct array { datatype *pstart;//数组首地址 int length;//长度 int sortstat;//有序或者无序 0 无序 1 有序 }; void init(struct array *parr); void initwithdata(struct array *parr,datatype data); void initwitharray(struct array *parr,datatype *pdata,int datalength); void show(struct array *parr); void addobject(struct array *parr,datatype data); void addobjects(struct array *parr,datatype *pdata,int datalength); void main() { struct array mydata; int a[10] = {1,2,3,4,5,6,7,8,9,10}; int b[6] = {11,12,13,14,15,16}; int c[5] = {17,18,19,20,21}; initwitharray(&mydata,a,10); show(&mydata); addobjects(&mydata,b,6); show(&mydata); addobjects(&mydata,c,5); show(&mydata); } void init(struct array *parr) { parr->pstart = NULL; parr->length = 0; parr->sortstat = 0; } void initwithdata(struct array *parr,datatype data) { parr->pstart=(datatype *)(sizeof(datatype)); *(parr->pstart) = data; parr->length = 1; parr->sortstat = 0; } void initwitharray(struct array *parr,datatype *pdata,int datalength) { parr->pstart= (datatype *)malloc(sizeof(datatype)*datalength); memcpy(parr->pstart,pdata,sizeof(datatype)*datalength); parr->length = datalength; parr->sortstat = 0; } void show(struct array *parr) { if(parr == NULL || parr->pstart == NULL || parr->length == 0) { printf("没有"); return; } else { printf("\n数组此时状态\n"); for(int i=0;i<parr->length;i++) { printf("%4d",parr->pstart[i]); } } printf("\n"); } void addobject(struct array *parr,datatype data) { if(parr != NULL) { if(parr->pstart == NULL || parr->length == 0) { initwithdata(parr,data); } else { parr->pstart = (datatype *)realloc(parr->pstart,parr->length*sizeof(datatype)+sizeof(datatype)); parr->pstart[parr->length] = data; parr->length++; } } else { printf("%s","addobject error"); } } void addobjects(struct array *parr,datatype *pdata,int datalength) { if(parr != NULL) { if(parr->pstart == NULL || parr->length == 0) { initwitharray(parr,pdata,datalength); } else { parr->pstart = (datatype *)realloc(parr->pstart,parr->length*sizeof(datatype)+datalength*sizeof(datatype)); memcpy(parr->pstart+parr->length,pdata,datalength*sizeof(datatype)); parr->length += datalength; } } else { printf("%s","addobjects error"); } }
时间: 2024-11-05 01:45:05