不少时候咱们使用matlab
、python
、c++
等进行矩阵操做,可是当进行实际操做的时候,咱们得把这些语言使用C去实现。c++
实现起来有两种方式:git
定义方式以下:github
typedef struct Matrix_t { unsigned int rows; unsigned int cols; void* data; //具体实现看我的需求 }Matrix;
新建和释放方式以下:数组
//Matrix* matrix = (Matrix*)malloc(sizeof(Matrix));//返回返回加入,参数进入不须要 /*Example void CreatMatrix(Matrix* src) { ....; } Matrix* CreatMatrix() { return ...; } */ matrix->data = (void*)malloc(sizeof(void)*rows*cols);
free(matrix->data); //free(matrix);//返回返回加入,参数进入不须要
遍历方式以下:函数
for (size_t i=0;i<rows;i++) for(size_t j=0;j<cols;j++) data[i*cols+j] = value;//operate
定义方式以下:测试
typedef struct Matrix_t { unsigned int rows; unsigned int cols; void** data; //具体实现看我的需求 }Matrix;
新建和释放方式以下:指针
//Matrix* matrix = (Matrix*)malloc(sizeof(Matrix));//返回返回加入,参数进入不须要 /*Example void CreatMatrix(Matrix* src) { ....; } Matrix* CreatMatrix() { return ...; } */ matrix->data = (void**)malloc(sizeof(void*)*rows); for(size_t i=0;i<rows;i++) matrix->data[i] = (void*)malloc(sizeof(void)*cols);
for(size_t i=0;i<rows;i++) free(matrix->data[i]); free(matrix->data); //free(matrix);//返回返回加入,参数进入不须要
遍历方式以下:rest
for (size_t i=0;i<rows;i++) for(size_t j=0;j<cols;j++) data[i][j] = value;//operate
当咱们使用动态数组、二叉树、自建vector等操做的时候,得常常用到malloc
和free
操做,其实这两个操做都很费时。code
好比:(1)新建和释放10000次的int
。(2)新建和释放1个大小为10000的int
内存。这两个笔者未亲自尝试,猜想前者不比后者快多少(或者更慢)。
先申请一块,不够就加倍申请
typedef struct Vector_t { unsigned int realNum; //当前使用数量 unsigned int TotalNum; //申请内存容量 void* data; }Vector;
if(realNum >= TotalNum-2)//保留两个预留位 { void* tmp = (void*)malloc(sizeof(void)*Vector->TotalNum*2.0);//不够就扩大两倍 for(size_t i=0;i<Vector->realNum;i++) tmp[i] = Vector->data[i];//复制以前数据 free(Vector->data);//释放以前数据 Vector->data = tmp;//指向新的数据 }
直接申请一大块内存,以后申请的空间所有在内存池以内
笔者没有亲自实现过内存池代码,只是使用别人已经写好的库(公司大神写的)
如下是Github上的库(仅供参考,笔者未测试):
typedef struct TreeNode_t//节点 { void data; //data struct storage void* children; void* parent; }TreeNode;
typedef struct TreeNode_t//一棵树 { unsigned int realNum; //当前使用数量 unsigned int TotalNum; //申请内存容量 TreeNode* treeNode; }TreeNode;
typedef struct Forest_t//一片深林 { unsigned int realNum; //当前使用数量 unsigned int TotalNum; //申请内存容量 TreeNode** treeNode; }Forest;
创建和释放方法参考1.1节所述,可变长度方法参考1.2节所述
举个例子:
当一系列函数A一、A二、A3.....是为完成某一个项目的,另一系列函数B一、B二、B3.....是为完成某一个项目的。固然你能够直接定义,经过名字取区分。。。
如何优雅的解决这个问题?
结构体中存放函数指针!!!
#include<stdio.h> #include<malloc.h> struct Hello{ void (*sayHello)(char* name); }; void sayHello(char* name){ printf("你好,%s\n",name); } int main(){ //struct Hello* hello=(struct Hello *)malloc(sizeof(struct Hello)); //hello->sayHello=sayHello; //hello->sayHello("a"); struct Hello hello= {sayHello}; hello.sayHello("a"); return 0; }
那么咱们就能够创建两个A和B结构体,把相应的函数指针放入其中便可。