C++ 中的 memset


在本节中,我们将了解 memset() 函数在 C++ 中的用途。该函数将字符值转换为无符号字符,并将其复制到由给定 str[] 指向的对象的前 n 个字符中。如果 n 大于字符串大小,则它是未定义的。

memset() 函数的语法

void* memset( void* str, int c, size_t n);

在此示例中,我们将使用一个字符串,然后将每个字符转换为其他字符,最长为 n。

示例

 实时演示

#include<bits/stdc++.h>
using namespace std;
int main() {
   char str[] = "Hello World";
   memset(str, 'o', 6); //take n = 6
   cout << str;
}

输出

ooooooWorld

memset() 可用于将所有值设置为 0 或 -1。但我们无法使用其他值,因为 memset() 按字节处理。

示例

 实时演示

#include<bits/stdc++.h>
using namespace std;
int main() {
   int array[10];
   memset(array, 0, sizeof(array));
   for(int i = 0; i<10; i++){ cout << array[i] << " "; }
      cout << endl;
      memset(array, -1, sizeof(array));
   for(int i = 0; i<10; i++){ cout << array[i] << " "; }
      cout << endl;
      memset(array, 3, sizeof(array));
   for(int i = 0; i<10; i++){ cout << array[i] << " "; }
      cout << endl;
}

输出

0 0 0 0 0 0 0 0 0 0
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
50529027 50529027 50529027 50529027 50529027 50529027 50529027
50529027 50529027 50529027

更新时间:30-07-2019

894 次浏览

开启你的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.