memset初始化数组的问题

今天才搞清楚,memset用于初始化数组,仅能初始化为0值,而不能初始化一个特定的值,这怎么能模糊了呢???

因此,如果对申请的一段存放数组的内存进行初始化,每个数组元素均初始化为特定的值,必须使用循环遍历来解决。

short* pBuffer = (short*)malloc(x_size*sizeof(short));
memset(pBuffer, 0x00, x_size*sizeof(short));
for (int j=0;j<x_size;j++)
{
    pBuffer[j] = idw_options.dfNoDataValue;
}

C++ Reference对memset函数的解释:

void * memset ( void * ptr, int value, size_t num );

Fill block of memory

Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).

也就是说,value只能是unsigned char类型,num是Number of bytes to be set to the value.

官方给的例子很好的说明了问题:

/* memset example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "almost every programmer should know memset!";
  memset (str,'-',6);
  puts (str);
  return 0;
}

output:

------ every programmer should know memset!
原文地址:https://www.cnblogs.com/yeahgis/p/3490500.html