我正在研究《数值食谱》中的一些例程,但我不明白在释放内存的实现中使用宏#define FREE_ARG char*。这是一段代码:
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#define NR_END 1
#define FREE_ARG char*
float *vector(long nl, long nh)
/* allocate a float vector with subscript range v[nl..nh] */
{
float *v;
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
if (!v) nrerror("allocation failure in vector()");
return v-nl+NR_END;
}
void free_vector(float *v, long nl, long nh)
/* free a float vector allocated with vector() */
{
free((FREE_ARG) (v+nl-NR_END));
\\ ^
\\ '----- why?
}
我的问题是:为什么内存以这种方式释放free((FREE_ARG) (v+nl-NR_END));?
最佳答案
这可能是一个非常糟糕的代码。注意
free()
采用参数类型 void *
。任何指针类型都可以隐式转换为 void *
,无需强制转换。
注意:
在这一行
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
Actor 阵容也不是必需的,应该避免。 See this discussion on why not to cast the return value of malloc()
and family in C
. 。这也是之前使用 bad 的原因之一。
关于c - 为什么使用宏 #define FREE_ARG char* 来分配由 malloc 分配的空闲内存(数值配方),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41535949/