头文件:
上述代码没有进行内存释放。。欢迎大家自己添加
#ifndef DYNAMIC_H_INCLUDED
#define DYNAMIC_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
struct data{
int *p;//动态数组头指针
int length;//动态数组长度
};
void inidata(struct data *pd);//初始化
void adddata(struct data *pd,int num);//动态增加元素
void addarray(struct data *pd,int *pp,int len);//动态增加数组
void disdata(struct data *pd);//显示
#endif // DYNAMIC_H_INCLUDED
源文件:
/***使用的是GCC编译器,个别变量定义有区别***/
#include <stdio.h>
#include <stdlib.h>
#include "dynamic.h"
int i;
int j;
int k;
void inidata(struct data *pd)
{
pd->p = NULL;//动态数组头指针
pd->length = 0;//动态数组长度
}
void adddata(struct data *pd,int num)
{
if(pd -> p == NULL)
{
pd->p = (int *)malloc(sizeof(int));
pd->length+=1;
pd->p[pd -> length - 1] = num;
}
else
{
pd -> p = (int *)realloc(pd -> p,(pd->length + 1)*sizeof(int));
pd -> length+=1;
pd -> p[pd -> length - 1] = num;
}
}
void addarray(struct data *pd,int *pp,int len)
{
if(pd ->p == NULL)
{
pd -> p = (int *)malloc(sizeof(int)*len);
for(i=0;i < len;i++)
{
pd -> p[pd -> length + i] = pp[i];
}
pd ->length += len;
}
else
{
pd -> p = (int *)realloc(pd -> p,(pd->length+len)*sizeof(int));
for(j=0;j<len;j++)
{
pd -> p[pd -> length + j] = pp[j];
}
pd -> length+=len;
}
}
void disdata(struct data *pd)
{
if(pd ->p == NULL)
{
printf("数组为空\n");
}
else
{
for(k=0;k < pd->length;k++)
{
printf("第%d个元素=%d\n",k,pd->p[k]);
}
}
}
int main()
{
int numa[10]={0,1,2,3,4,5,6,7,8,9};
struct data data1;
inidata(&data1);
addarray(&data1,numa,10);
disdata(&data1);
adddata(&data1,10);
adddata(&data1,20);
adddata(&data1,30);
adddata(&data1,30);
disdata(&data1);
adddata(&data1,50);
adddata(&data1,60);
disdata(&data1);
return 0;
}
上述代码没有进行内存释放。。欢迎大家自己添加