今天才搞清楚,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!