memset

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
shamim
A great helper
Posts: 498
Joined: Mon Dec 30, 2002 10:10 am
Location: Bozeman, Montana, USA

memset

Post 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.

Grow
New poster
Posts: 4
Joined: Fri Mar 22, 2002 2:00 am
Location: Poland

Post by Grow »

double d;
int i;

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

junjieliang
Experienced poster
Posts: 169
Joined: Wed Oct 31, 2001 2:00 am
Location: Singapore

Post 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.

ChristopherH
New poster
Posts: 31
Joined: Sun Feb 23, 2003 9:18 pm
Location: Waterloo, Ontario, Canada

Post 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.

ec3_limz
Learning poster
Posts: 79
Joined: Thu May 23, 2002 3:30 pm
Location: Singapore

Post 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.

Post Reply

Return to “C++”