Jump to content

Best way to wipe an array?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
7 replies to this topic

#1
Uninverted

Uninverted

    Newbie

  • Members
  • PipPip
  • 11 posts
What's the 'best' way to make all of the elements in an array null (in terms of efficiency and simplicity)? The first thing I thought of was a loop, like, say,

while (array[i] != "") {
  array[i] = "";
}
But that doesn't really seem right for some reason. I though of using { }, but I'm not sure how that would work, exactly. Any ideas?
My other car return the first item in a list.

#2
broncoslb

broncoslb

    Learning Programmer

  • Members
  • PipPipPip
  • 34 posts
Well it sort of depends on the type of the array. If your using chars or ptrs then something like this should be efficient:


int i=0;

while(array[i] != NULL){

    array[i] = NULL;

    i++;

}



#3
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,720 posts
Just call ZeroMemory(pointer,size)

#4
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
Watch out with the ZeroMemory-function, because it's a Win32 API function. It's probably a good alternative, if you're on Windows, but won't work on other platforms.

I would use the standard-C function, memset. I don't know about how efficient it is, though.
#include <string.h>
// ...
memset(my_array, '\0', sizeof(my_array[0]) / sizeof(my_array));


#5
TkTech

TkTech

    The Crazy One

  • Moderators
  • 1,396 posts
memset is very efficient.

#6
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,720 posts
v0id: your code won't work - the last parameter should be sizeof(my_array) / sizeof(my_array[0]). Sorry, I'm anal-retentive.

#7
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
Yes.

#8
Rothzael

Rothzael

    Newbie

  • Members
  • PipPip
  • 27 posts
I dynamically create them and then use free();
Programming Assignment Help
while(true) { cout << "Idiot!" << endl; }