$ cat main.c
//#include"dynaicArray.h"
//#pragma once
//#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//容量和大小的区别:一个是能装多少,一个是装了多少。
struct dynamicArray
{
//维护真实在堆区开辟数组指针
void** pAddr;
//数组的容量
int m_Capacity;
//数组的大小
int m_Size;
};
struct PERSON
{
char name[64];
int age;
};
//初始化数组
struct dynamicArray* init_dynamicArray(int capacity);
//插入数组
void insert_dynaminArray(struct dynamicArray* arr, void* data, int pos);
//遍历动态数组
void foreach_dynamicArray(struct dynamicArray* arr, void(*myprint)(void*));
//初始化数组 参数 初始化数组容量 返回值 数组指针
struct dynamicArray* init_dynamicArray(int capacity)
{
if (capacity <= 0)
{
return NULL;
}
//给数组分配内存
struct dynamicArray* arr = malloc(sizeof(struct dynamicArray));
if (arr == NULL)
{
return NULL;
}
//给属性初始化
arr->pAddr = malloc(sizeof(void *)* capacity);
if (arr->pAddr == NULL)
{
return NULL;
}
//容量初始化
arr->m_Capacity = capacity;
//大小初始化
arr->m_Size = 0;
return arr;
}
//插入数组
void insert_dynaminArray(struct dynamicArray* arr, void* data, int pos)
{
if (arr == NULL)
{
return;
}
if (data == NULL)
{
return;
}
if (pos < 0 || pos > arr->m_Size)
{
//尾插
pos = arr->m_Size;
}
//判断数组是否满了
if (arr->m_Size == arr->m_Capacity)
{
//计算新内存的大小
int newCapacity = arr->m_Capacity * 2;
//开辟新空间
void** newSpace = malloc(sizeof(void* ) * newCapacity);
if (newSpace == NULL)
{
return;
}
//将原空间下数据拷贝到新空间下
memcpy(newSpace, arr->pAddr, sizeof(void*)* arr->m_Capacity);
//释放原有空间
free(arr->pAddr);
//更改指针指向
arr->pAddr = newSpace;
//更改新的容量
arr->m_Capacity = newCapacity;
}
//将新元素插入到数组中指定位置
for (int i = arr->m_Size - 1; i >= pos; i--)
{
//数据往后移动
arr->pAddr[i + 1] = arr->pAddr[i];
}
//将数据插入到指定位置
arr->pAddr[pos] = data;
//更新数组大小
arr->m_Size++;
}
//遍历
void foreach_dynamicArray(struct dynamicArray* arr, void(*myPrint)(void*))
{
if (arr == NULL)
{
return;
}
for (int i = 0; i < arr->m_Size; i++)
{
myPrint(arr->pAddr[i]);
}
}
$ gcc-debug -o main main.c
/usr/bin/ld: /usr/lib/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../lib/Scrt1.o: in function `_start':
(.text+0x1b): undefined reference to `main'
collect2: error: ld returned 1 exit status
$
|