I have noticed unexpected behavior of memset() when used with dynamic arrays.
// This works well, sets value of each index = 0
int dp[5];
memset(dp, 0, sizeof(dp));
// This one doesn't work as expected, there are garbage values at some indexes
int *dp = new int[5];
memset(dp, 0, sizeof(dp));
// And this one works as expected
int *dp = new int[5];
memset(dp, 0, sizeof(dp[0]) * n);
What defines the reason for this unexpected behavior?
EDIT:
I understand that sizeof(dp) gives the size of pointer where as sizeof(dp[0]) gives the size of dp[0]. My main concern is if first one is working fine with the pointer size i.e. sizeof(dp) then why isn't the second one working similarly, why are there garbage values?
This
declares
dpas an array of 5 integers, aint[5]. Heredpis not a pointer. It is an array. Arrays are not pointers. Thesizeof dpis5 * sizeof int.On the other hand, this:
declares
dpas a pointer toint, aint*. Thesizeof dpis that of aint*.Important: Pointers are not arrays and arrays are not pointers. The
dphere is very different to thedpabove. Heredpis a pointer to a singleint, the first element of the dynamically allocated array.When
dpis a pointer, thendp[0]is equivalent to*(dp + 0), hence5 * sizeof dp[0]is the total size of the array whendppoints to the first element of an array with5integers.Consider this:
Possible output is:
Here the size of a integer is 4 while the size of a pointer to integer is 8. Those numbers can differ, but the size of an array of 5 integers is always
5 * sizeof(int)and typicallysizeof(int*)is much smaller thansizeof(int[5]).About your edit...
See above. In the first example
dpis not a pointer. When you declaredpasint dp[5];thendpis not a pointer. It is an array. Arrays are not pointers.int* dp = ...on the other hand declaresdpas a pointer to integer.PS: Use a vector instead of manually managed c-arrays and skip the usage of
memset: