memset()函数及其简单用法

函数原型:

//复制字符 c(一个无符号字符)到参数 str 所指向的字符串的前 n 个字符,c一般为0
void *memset(void *str, int c, size_t n)

作用:
定义变量时一定要进行初始化,尤其是数组和结构体这种占用内存大的数据结构。在使用数组的时候经常因为没有初始化而产生“烫烫烫烫烫烫”这样的野值,俗称“乱码”。对于数组或者结构体的初始化可以通过memset函数实现。

  1. 为新申请的内存进行初始化工作
  2. 清空一个结构类型的变量或数组

代码示例

#include "stdafx.h"
#include 

using namespace std;

struct RESULT {
	int id;
	double length;
	char name[20];
};

int main()
{
	char chs[10];
	memset(chs,0,sizeof(chs));
	cout << "sizeof(chs)=" << sizeof(chs) << "\tchs=" << chs << endl;
	memcpy(chs,"hello",sizeof("hello")/sizeof(char));
	cout << "sizeof(chs)=" << sizeof(chs) << "\tchs=" << chs << endl;

	RESULT result_;
	memset(&result_, 0, sizeof(result_));
	cout << "sizeof(result_)=" << sizeof(result_) << endl;
	cout << result_.id << "\t" << result_.length << "\t" << result_.name << endl;
	result_ = { 1,20.2,"lusx" };
	cout << "sizeof(result_)=" << sizeof(result_) << endl;
	cout << result_.id << "\t" << result_.length << "\t" << result_.name << endl;

	cout << "after offset using memset..." << endl;
	memset(chs, 0, sizeof(chs) / chs[0]);
	cout << "sizeof(chs)=" << sizeof(chs) << "\tchs=" << chs << endl;
	memset(&result_, 0, sizeof(result_));
	cout << "sizeof(result_)=" << sizeof(result_) << endl;
	cout << result_.id << "\t" << result_.length << "\t" << result_.name << endl;

	system("pause");

    return 0;
}

你可能感兴趣的:(C++学习笔记,c++,开发语言,后端)