memset初始化数组的问题(不能初始化特定的数)

版权声明:转载请注明出处 https://blog.csdn.net/TY_GYY/article/details/81712433

memset用于初始化数组,仅能初始化为0值,

而不能初始化一个特定的值。

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

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.

#include <bits/stdc++.h>
using namespace std;
int main ()
{
  int str[10];
  memset (str,9,sizeof(str));
  for(int i=0;i<9;i++)
    cout<<str[i];
  return 0;
}
//output :151587081151587081151587081151587081151587081151587081151587081151587081151587081

初始化字符

#include <bits/stdc++.h>
using namespace std;
int main ()
{
  char str[10];
  memset (str,'a',sizeof(str));
  str[9]='\0';
  puts(str);
  return 0;
}
//output :aaaaaaaaa

复制代码

猜你喜欢

转载自blog.csdn.net/TY_GYY/article/details/81712433