Trying to understand the purpose of memset

I'm looking at Matrix addition samples and in one of them I noticed the use of memset in the Identity matrix function:

1
2
3
4
5
6
7
// Class Matrix4x4
void Matrix4x4::Identity()
{
	memset(this, 0, sizeof(Matrix4x4)); // Why?

	m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1.0f;
}


The simplest example of memset I found was at MSDN:

1
2
3
4
5
   char buffer[] = "This is a test of the memset function";

   printf( "Before: %s\n", buffer );
   memset( buffer, '*', 4 );
   printf( "After:  %s\n", buffer );


I understand what happened, and what happens if I change the last argument of memset, more characters in the buffer will get replaced.

What I don't understand is the purpose of memset, what are the benefits of using it, and most importantly how is it being used in this Identity Matrix function.

I especially don't understand the use of this. I know it's saving to this (current class), but where? The MSDN buffer sample was easy, I'm lost when saving to a class object.

I'm sure my understanding of memset is very incomplete too.
Last edited on
closed account (48bpfSEw)
http://www.cplusplus.com/reference/cstring/memset/?kw=memset

It is a trick no 7 to initialize all attributes of the class, but I would prefer not to do so.

1
2
3
void Matrix4x4::Identity() {
	memset(this, 0, sizeof(Matrix4x4));
}


I would rather initialize them on a clear way:

1
2
3
4
  
  this->attributename1 = "";   // if it's a string;
  this->attributename2 = 0.0; // if it's a double
  etc.


Oh that's all it is? I thought there was some performance gain. Thanks.

One last question, how do I know what memset is going to initialize when I throw in a class like that, how does it choose what to initialize?

I'm guessing that's what the third argument is for.
closed account (48bpfSEw)
this points to the memory where your current instance of the class is.
sizeof(Matrix4x4) returns the size of the structure. that is all what memset needs to start its job: overwritting the memory from the position "this" with the amount delivert from sizeof with a specific value e.g. 0


it is the same like :

1
2
3
  for (int i=0; i<iSize; i++) 
    (*((char*)this)+i)) = 0;
  


isn't it ugly? ^^

typeconversion is a special topic in c++
don't convert your types like I did above!
Last edited on
Perfect, now I got it, thanks @Necip.

It's actually a very convenient tool, at least for Vectors, Matrices, etc. One line and everything is instantiated at 0.
Topic archived. No new replies allowed.