#include
#include
#include
struct ARRAY{
int cnt;
int *parr;
};
bool init(struct ARRAY *p,int len)
{
p->parr=(int *)malloc(sizeof(int)*len);
if(p==NULL){
printf("invalid");
return false;
}else{
return true;
}
}
void append(struct ARRAY *p,int number)
{
p->parr[p->cnt]=number;
(p->cnt)++;
return;
}
int main()
{
struct ARRAY array;
if(init(&array,10)){
append(&array,1);
append(&array,2);
append(&array,3);
}
free(array);
return 0;
}
不用 free(); 这个区域会在函数完成后自动销毁!
代码如下:
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
struct ARRAY {
int cnt;
int *parr;
};
bool init(struct ARRAY *p, int len) {
p->parr = (int *)malloc(sizeof(int) * len);
p->cnt = 0;
if (p == NULL) {
printf("invalid");
return false;
} else {
return true;
}
}
void append(struct ARRAY *p, int number) {
p->parr[p->cnt] = number;
(p->cnt)++;
return;
}
int main() {
struct ARRAY array;
if (init(&array, 10)) {
append(&array, 1);
append(&array, 2);
append(&array, 3);
}
for( int i = 0 ; i < 3 ; i++ ){
printf("%d = %d\n",i,(int)(array.parr[i]));
}
return 0 ;
}