I have another memset question. It appears as if the code I am editing may have some issues (or it’s not done the same way in different files)
A::LRM las[9]; //A and LRM are both structures with BOOLS and INTS
memset(&las, 0, sizeof(las));
typedef Sec SecArray[16];
SecArray rad_array;
memset(rad_array, 0, sizeof(SecArray));
The second example appears to be correct because rad_array is the same as the first position in the array. Then the sizeof(SecArray)) would make sense. The first one doesn’t seem correct to me. All structs are just BOOLs and INTS nothing dynamic in them.
My understanding from my other post about memset was that it followed this format.
memset("pointer to object", "what to set it to", "size of object")
Can anyone tell me what exactly is going on here if I am incorrect with my theory.
Both calls to
memsetare correct. Bothsizeof(las)(or justsizeof las) andsizeof(SecArray)will return the size of the entire array.If you are worried about the first argument, then again, both will work. The pointer to the entire array (
&las) or the pointer to the first element (rad_arrayin this context) will work equally well withmemset.In general, with regard to
sizeofusage, I would recommend using the first approach, since it is type-independent. A good programming practice is to avoid mentioning type names in your statements, i.e. keep type names restricted to declarations as much as possible.As for the first argument, in case of an array it is a matter of preference, but in general I would say that if you have an object of type
Tand you want to fill it with zeros by using
memset, you’d normally do it asI don’t see why an array should be an exception from that rule (especially if the exact nature of the type is hidden behind a typedef-name). The above
memset(&t, ...will work regardless of whetherTis an array type, a struct type or any other type. I don’t see why one should suddenly drop the&just becauseTis an array type. Quite the opposite, I’d keep that&to keep the code as type-independent as possible.Finally, in C++ in both cases the better way to do it would be not to use
memsetat all and just doinstead.