0

If you want to set an entire array to -1 is better to cycle through it with a for loop like this?

for (int i = 0; i < 100; ++i){
  array[i] = -1;
}

Or use memset like this?

memset (array,-1,100);
3
Contributors
2
Replies
29
Views
2 Years
Discussion Span
Last Post by Maritimo
0

It rather depends on the type of the array. If it's anything but some variant of char, I'd recommend using a loop to avoid nasties by diddling with individual bytes of a multi-byte type.

0

void* memset( void* dest, int ch, std::size_t count );
Converts the value ch to unsigned char and copies it into each of the first count characters of the object pointed to by dest.

This means that if your destination can´t be looked as unsigned chars, memset will not work. For example:

#include <iostream>
#include <cstring>

int main()
{
    int a[20];
    std::memset(a, 0, sizeof(a));     /* Note 0 */
    for (int ai : a) std::cout << ai;
}

will work; but:

#include <iostream>
#include <cstring>

int main()
{
    int a[20];
    std::memset(a, 2, sizeof(a));     /* Note 2 */
    for (int ai : a) std::cout << ai;
}

will not!

In conclusion, if you can use memset, it is better because it is faster. The trick is hiden in the words: if you can use. In the case of -1, you can use memset. However, for clarity and if the speed is not an issue, I adhere to the recommendation of deceptikon.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.