1.源码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
//数组输出
void output(int *arr, int n)
{
if(n > 0)
{
int i;
for(i=0; i<n-1; i++)
{
printf("%d ", arr[i]);
}
printf("%d\n", arr[i]);
}
}
//数组初始化
int init(int **arr, int n)
{
*arr = (int *)malloc(n*sizeof(int));
memset(*arr, 0x00, n*sizeof(int));
return n;
}
//数组扩容
int resize(int **arr, int n)
{
int *tmp = *arr;
if(*arr == NULL)
{
return 0;
}
*arr = (int *)malloc(n*2*sizeof(int));
memset(*arr, 0x00, n*2*sizeof(int));
memcpy(*arr, tmp, n*sizeof(int));
free(tmp);
return n*2;
}
//数组插入元素
int insert(int **arr, int *size, int n, int elem, int index)
{
int i;
if(index < 0 || index > n)
{
printf("超出数组实际元素范围\n");
return n;
}
if(n + 1 > *size)
{
*size = resize(arr, *size);
}
for(i=n-1; i>=index; i--)
{
(*arr)[i+1] = (*arr)[i];
}
(*arr)[index] = elem;
return n+1;
}
//数组删除元素
int delete(int *arr, int n, int index)
{
int i;
if(index < 0 || index > n)
{
printf("超出数组实际元素范围\n");
return n;
}
for(i=index; i<n-1; i++)
{
arr[i] = arr[i+1];
}
arr[i] = 0x00;
return n-1;
}
int main()
{
int *array = NULL;
int size = 4;
int n = 0;
init(&array, size);
output(array, n);
n = insert(&array, &size, n, 3, 0);
output(array, n);
n = insert(&array, &size, n, 7, 1);
output(array, n);
n = insert(&array, &size, n, 9, 2);
output(array, n);
n = insert(&array, &size, n, 5, 3);
output(array, n);
n = insert(&array, &size, n, 6, 1);
output(array, n);
printf("size=%d\n", size);
return 0;
}
2.编译源码
$ gcc -o example example.c
3.运行及其结果
$ ./example
3
3 7
3 7 9
3 7 9 5
3 6 7 9 5
size=8
网友评论