memset () function

Source: Internet
Author: User

Memset
Required header files <memory.h> or <string.h> memset<wchar.h> wmemset
The function describes void *memset (void *s, int ch, size_t n); function interpretation: replaces the first n bytes in s (typedef unsigned int size_t) with ch and returns S. Memset: The effect is to populate a block of memory with a given value, which is the fastest way to clear 0 operations on a larger struct or array [1]. Common mistakes First: the position of CH and n is reversed. Be sure to remember that if you want to clear a char a[20], it must be memset (a,0,20), not memset (a,20,0); second: Over-use memset, I think these programmers may have some sort of psychological shadow, They are afraid of uninitialized memory, so they will write code like this:
12345 charbuffer[4];memset(buffer,0,sizeof(char)*4);strcpy(buffer,"123");////////////////////////////////////////////////////////////////////////"123"中最后隐藏的‘\0‘占一位,总长4位。
The memset here are superfluous. Because this memory is covered immediately, 0 is meaningless. Another: The following is not redundant, because some compilers allocate space, the default value in memory is not 0:
1234567 charbuffer[20];memset(buffer,0,sizeof(char)*20);memcpy(buffer,"123",3);////////////////////////////////////////////////////////////////////////这一条的memset并不多余,memcpy并没把buffer全部覆盖,如果没有memset,///////////用printf打印buffer会有乱码甚至会出现段错误。///////////如果此处是strcpy(buffer,"123");便不用memset,strcpy虽然不会覆盖buffer但是会拷贝字符串结束符
Third: In fact, this error strictly speaking can not be used wrong memset, but it often in the use of memset occasions appear
1234567 intsome_func(structsomething*a){memset(a,0,sizeof(a));}
The reason for this error is that the VC function in the process of the pointer demotion, resulting in sizeof (a), the return is a something* pointer type size of the number of bytes, if it is 32 bits, is 4 bytes. Frequently asked Questions: Why use memset zero? memset (Address), often see this usage, in fact, when allocating data, the rest of the space will be zeroed. A: 1. If you do not empty, you may have wild values in the test. You do the following test to see the results ()
123456789101112131415161718 #include"iostream.h"#include"string.h"#include<afx.h>intmain(){charbuf[5];CStringstr;CStringstr1;CStringstr2;memset(buf,0,sizeof(buf));for(inti=0;i<5;i++){str.Format("%d",buf[i]);str1+=str;}str2.Format("%d",str1);cout<<str2<<endl;system("pause");return0;}
This write, there is no memset, the output is the same ⒉ is not! Especially for the character pointer type, the remainder is usually not 0, it is advisable to make an experiment, define a character array, and enter a string of characters, if not memset implementation of zero, using the MessageBox display will be garbled (0 means null, if there is, the default character ends, Do not output the following garbled) Q: The following demo is possible, you can set the value of the elements in the array to character 1,
1234567891011 #include<iostream>#include<cstring>usingnamespacestd;intmain(){chara[5];memset(a,‘1‘,5);for(inti=0;i<5;i++)cout<<a[i]<<"";system("pause");return0;}
And, the following program wants to set the element value in the array to 1, but it is not feasible
12345678910111213 #include < Iostream> #include <cstring> #include <windows.h> USINGNAMESPACESTD; Intmain () { inta[5]; memset (a,1,20); //If this is changed to memset (a,1,5*sizeof (int)), it is not possible because memset is assigned by byte. for (inti=0;i<5;i++) cout<<a[i]<< "" ; system ( "pause" ); Return0; }
The question is: 1, why is the first program possible, and the second one not? Because the first program's array A is a character type, the character type occupies the memory size is 1Byte, and the Memset function is also assigned in bytes, so you output no problem. and the second program A is integer, using memset or byte assignment, so that after the assignment, the value of each array element is actually 0x01010101, or decimal 16843009. 2, do not want to use for, or while loop to initialize int a[5]; Can you do that? (There is not a function like memset () initialized) if used memset (a,1,20), (in fact, the result is the same as memset (a,1,5*sizeof (int)) is the memory of a pointed to the 20 bytes of the assignment, Each is filled with a ascⅱ of 1 characters, converted to binary, 1 is 00000001, and takes up one byte. An int element is 4 bytes, and one is 0x01010101, which is equal to 16843009, which completes the assignment of an INT element.
Program examplesEdit
12345678910111213 #include<string.h>#include<stdio.h>#include<memory.h>intmain(void){charbuffer[]="Helloworld\n";printf("Bufferbeforememset:%s\n",buffer);memset(buffer,‘*‘,strlen(buffer));printf("Bufferaftermemset:%s\n",buffer);return0;}
Output Result:
12 Bufferbeforememset:HelloworldBufferaftermemset:***********
Compile platform: Microsoft Visual c++6.0 also does not necessarily have to set the content to the Ascⅱ value specified by CH, and it can be int or other type, not necessarily char type. For example, this is the following:
123456789 intarray[5]={1,4,3,5,2};for(inti=0;i<5;i++)cout<<array[i]<<"";cout<<endl;memset(array,0,5*sizeof(int));for(intk=0;k<5;k++)cout<<array[k]<<"";cout<<endl;
The result of the output is:
12 1435200000
The parameters for the subsequent table size are in bytes, so it is not the default 1 (character) for int or others. and the size of int may be different on different machines, so it is best to use sizeof (). Note that memset is a byte operation, so the above procedure should be changed to
123456789 intarray[5]={1,4,3,5,2};for(inti=0;i<5;i++)cout<<array[i]<<"";cout<<endl;memset(array,1,5*sizeof(int));//注意这里与上面的程序不同for(intk=0;k<5;k++)cout<<array[k]<<"";cout<<endl;
The result of the output is:
12 143521684300916843009168430091684300916843009
Why is it? Because Memset is assigned in bytes to 4 bytes of the memory that the array points to, each is populated with Ascⅱ 1 characters, and 1 is 00000001, or one byte, after the binary is converted. An int element is 4 bytes, and the unity is
1 00000001000000010000000100000001
is equal to 16843009, it completes the assignment of an INT element. So it is not advisable to use Memset to assign an initial value to a non-character array! For example, there is a struct some x, which can be as clear as 0:
1 memset(&x,0,sizeof(Some));
If it is an array of structs some x[10], you can do this:
1 memset(x,0,sizeof(Some)*10);
memset function Detailed description 1. void *memset (void *s,int C,size_tn) General effect: Sets the value of the first n bytes of the open memory space s to the value C. 2. Example
1234567891011 intmain(){char*s="GoldenGlobalView";clrscr();memset(s,‘G‘,6);//貌似这里有点问题//这里没有问题,可以编译运行,楼主在这里将右括号和分号变成了中文输入法//单步运行到这里会提示内存访问冲突//肯定会访问冲突,s指向的是不可写空间。printf("%s",s);getchar();return0;}
"The memory access violation in the above example should be because s is placed as a constant in the program storage space and if modified to char s[]=" Golden Global View "; there is no problem. "" should be no problem, like a string pointer can, not read-only memory, can run normally "" This instance can be compiled and run normally, not as the landlord said need Char s[] "3. The memset () function is commonly used for memory space initialization. Such as:
12 charstr[100];memset(str,0,100);
4. The profound connotation of memset (): Used to set a memory space to a certain character, generally used in the definition of the string is initialized to ' memset (A, ' ", sizeof (a)); 5. Add: A bit of tricks memset can easily empty a variable or array of a struct type. Such as:
123456 structsample_struct{charcsName[16];intiSeq;intiType;};
For variables
1 structsample_strcutstTest;
In general, the method of emptying the sttest:
123 stTest.csName[0]={‘\0‘};stTest.iSeq=0;stTest.iType=0;
It is very convenient to use memset:
1 memset(&stTest,0,sizeof(structsample_struct));
If it is an array:
1 structsample_structTEST[10];
The
1 memset(TEST,0,sizeof(structsample_struct)*10);
In addition, if there are arrays in the struct, it is necessary to initialize the array separately.

Go from Elsewhere

Go from Elsewhere

memset () function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.