【发布时间】:2020-04-19 13:25:15
【问题描述】:
搞乱/学习 C。我想要一个用于将堆栈值移动到堆中的单线器,这是我能想到的最好的方法。
#define defheapify(nm, T, sz) \
T* heapify_##nm (const T x) { \
T *nx = malloc(sz); \
nx[0] = x; \
return nx; \
}
defheapify(char, char, sizeof(char));
defheapify(uchar, unsigned char, sizeof(unsigned char));
defheapify(short_int, short int, sizeof(short int));
defheapify(ushort_int, unsigned short int, sizeof(unsigned short int));
defheapify(int, int, sizeof(int));
defheapify(uint, unsigned int, sizeof(unsigned int));
defheapify(long_int, long int, sizeof(long int));
defheapify(ulong_int, unsigned long int, sizeof(unsigned long int));
defheapify(long_long_int, long long int, sizeof(long long int));
defheapify(ulong_long_int, unsigned long long int, sizeof(unsigned long long int));
defheapify(float, float, sizeof(float));
defheapify(double, double, sizeof(double));
defheapify(long_double, long double, sizeof(long double));
它似乎有效:
short int *si = heapify_short_int(20);
printf("%d\n", ((int*)si)[0]); /* => 20 */
有没有更好的方法来做到这一点?
【问题讨论】:
-
你为什么要这样做?
-
除了可能有
*nx = x而不是使用[0]并添加检查以确保malloc不会返回NULL我唯一的原因就是。 -
分割堆的好方法。
-
@EugeneSh。无论您是通过为所有类型定义函数,还是在每个地方写出 malloc 代码,都会发生这种情况。
-
@Christian Gibbons,我的第一个想法是他们想要一个初始化分配器,但初始化只适用于简单类型。所以是的,为什么要动态地动态分配简单的值?
标签: c malloc dynamic-memory-allocation