【发布时间】:2010-04-05 09:49:34
【问题描述】:
我不时使用以下代码生成矩阵样式数据结构
typedef double myType;
typedef struct matrix_t{ |Compilation started at Mon Apr 5 02:24:15
myType **matrix; |
size_t x; |gcc structreaderGeneral.c -std=gnu99 -lz
size_t y; |
}matrix; |Compilation finished at Mon Apr 5 02:24:15
|
|
matrix alloc_matrix(size_t x, size_t y){ |
if(0) |
fprintf(stderr,"\t-> Alloc matrix with dim (%lu,%lu) byteprline=%lu bytetotal:%l\|
u\n",x,y,y*sizeof(myType),x*y*sizeof(myType)); |
|
myType **m = (myType **)malloc(x*sizeof(myType **)); |
for(size_t i=0;i<x;i++) |
m[i] =(myType *) malloc(y*sizeof(myType *)); |
|
matrix ret; |
ret.x=x; |
ret.y=y; |
ret.matrix=m; |
return ret; |
}
如果我的矩阵中的条目需要不同类型的类型,我会相应地更改我的 typedef。
现在我需要 2 个不同类型的矩阵,一个简单的解决方案是复制/粘贴代码,但是有什么方法可以做一个更通用的实现。
谢谢
编辑: 我应该澄清它在 c 中而不是 c++ 中。 抱歉没有说清楚。
【问题讨论】:
-
那为什么是 C++ 标签呢?而 C 甚至没有模板!。
-
这看起来像是一种情况,您可以合法地滥用预处理器,通过宏和令牌粘贴为您提供穷人的模板模拟。
-
如果它是合法的,那么它不是滥用。这看起来像是您可以合法地诉诸预处理器的使用的情况;-)
-
@Steve - 也许是这样,但我怀疑在实施过程中仍然会口头滥用预处理器。 ;-)
-
@Paul R,滥用,你的意思是它不完全是类型安全的吗?我认为这是给定的?
标签: c alloc generic-collections