我正在为指针数组分配内存。结果具有固定数量的项目,我希望将它们全部初始化为NULL
。
char **result = (char **)calloc(12, sizeof(char *));
我现在可以肯定的元素result[0]
到result[11]
是NULL
?
作为0
-ing了一个指针p
做的价值
memset(p, 0, sizeof(p));
没必要等于做
p = NULL;
在每个平台上,您都会放心地这样做:
SomeType ** result = malloc(12 * sizeof(*result));
if (NULL != result)
{
for (size_t i = 0; i < 12; ++i)
{
result[i] = NULL;
}
}
您可以将其包装在一个宏中,如下所示:
#define ALLOCARRAY(result, size) \
do { \
result = malloc(size * sizeof(*result)); \
if (NULL != result) \
{ \
for (size_t i = 0; i < size; ++i) \
{ \
result[i] = NULL; \
} \
} \
} while (0)
然后使用如下宏:
#include <stdlib.h>
[...]
SomeType ** result = NULL;
ALLOCARRAY(result, 12);
if (NULL == result)
{
/* Handle error here. */
}
else
{
/* Use array here. */
/* Free array. */
free(result);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句