sizeof string pointer

Hi ,
I have a class in which i have a private variable as

1
2
3
private:
	static const int size = 100;
	const string* stack[size];

now in the constructor of the class i have the memset as
 
             memset(stack , 0 , size * sizeof(string*));


I am not able to understand why it is written sizeof(string*) in the memset .
can any one clear understanding.
Thanks in advance .
memset takes the number of bytes to zero out.

The number of bytes occupied by the array is equal to the number of elements
in the array times the size of each element. Each element is a (const string*).
The goal is to write 0s to every byte in the stack array.

The stack array is an array of 100 string pointers.

The number of bytes in the stack array is 100 * the size of one string pointer.

The sizeof operator is needed because the size of a pointer is platform dependent.

Does that answer your question?
Now i got it ...
yes it does PanGalactic answers and clear my understanding .


Thanks both of you .
Seems like a questionable approach, IMO. Why not use an STL algorithm, like fill, and assign 0 to each element?
memset() is always faster.
memset is also more confusing and I can't believe that it is so much faster that it is going to make a meaningful difference. It is obviously a preference but std::fill works per element while memset works per byte. With fill you only need the array size and the sizeof call is not needed. I compiled the following and looked at assembly. The fill was completely inlined. However the memset function was actually called and I couldn't see the code for it. Nothing jumped out at me that led me to believe that using memset would result in better performance. The performance would certainly be different, somehow, but I am not even sure if it would be worth anyone's time to run a profile and check. The cast is kind of annoying to have to write though but it seems to be needed only because we are dealing with pointers.


1
2
3
4
5
6
7
8
9
10
11
int main() 
{ 
	const int size = 100; 
	const string* stack[size]; 
 
	std::fill(stack, stack + size, reinterpret_cast<const string*>(0)); 
 
	memset(&stack[0], 0, size * sizeof(string*)); 
	 
	return 0; 
} 
Last edited on
As kempofighter has pointed out, the fill approach closely models the conceptual intent of the call, whereas the memcpy does something different--which, happens to result in correct behavior.

More importantly, consider a future change where the pointer is replaced with a smart pointer. The smart pointer will presumably understand an element-by-element assignment to 0, where as the memcpy might not be what you're after.
Last edited on
Never mind. memset() and memcpy() only make a difference when dealing with arrays of POD types. This is because they are usually copied by calling memcpy(). A single call is better than many.

Why not use an STL algorithm, like fill, and assign 0 to each element?
How about terseness?
Topic archived. No new replies allowed.