Page 1 of 1

memset

Posted: Sat May 03, 2003 12:13 pm
by shamim
I know that memset can be used to assign values to a character array in the following way:

char str[100];
memset(str,'*',10);

now can i use memset to assign values to other data types such as double. If so how can I achieve this.

Posted: Sat May 03, 2003 1:51 pm
by Grow
double d;
int i;

memset(&d,0,sizeof(double));
memset(&i,0,sizeof(int));

Posted: Sat May 03, 2003 2:00 pm
by junjieliang
You can do the same with arrays:

Code: Select all

double d[100];
int a[100];

memset(d, 0, sizeof(d));
memset(a, 0, sizeof(a));
However, do take note that since int and double are not 1 byte, you cannot do things like memset(a, 1, sizeof(a)) and expect a[0..99] to be 1.

Posted: Mon May 05, 2003 6:44 pm
by ChristopherH
The C++ STL function "fill(iterator, iterator, value)" may be useful if you need to perform more complicated initializations.

[cpp]
#include <algorithm>

using namespace std;

double a[100];
vector<string> b;

void foo() {
fill(a, a+100, 3.1415);
fill(b.begin(), b.end(), "hello");
}
[/cpp]

I have not benchmarked memset vs. fill on UVA, but I think memset is faster for zeroing things.

Posted: Mon Jun 09, 2003 3:28 pm
by ec3_limz
However, do take note that since int and double are not 1 byte, you cannot do things like memset(a, 1, sizeof(a)) and expect a[0..99] to be 1.
You can use memset to set an array all to 0 or -1. I do not know of any other values that will work, unless you memset a char array of course.