MooMooCoding
MooMooCoding

Reputation: 329

How to 'clear' an array of strings?

After the initialisation in main(void):

char *params[MAXPARAMS] = {NULL};

params is passed to different functions.

How can I 'reset' the array just as it was during initialisation (after some other functions stored strings in it)?


Edit: params is used as a parameter list, so it might not be fully populated after certain operations. By 'reset' I meant: I want no string values left inside the array, like how you clear a string array in Java, but keeping the same array size.

Upvotes: 1

Views: 3588

Answers (3)

chux
chux

Reputation: 153348

If params has allocated strings, first free the allocations

for (size_t i=0; i<MAXPARAMS; i++) free(params[i]);

To get everything back to NULL

for (size_t i=0; i<MAXPARAMS; i++) params[i] = NULL;
// or 
memset(params, 0, sizeof params);

Suggest combining:

for (size_t i=0; i<MAXPARAMS; i++) { 
  free(params[i]);
  params[i] = NULL;
}

Upvotes: 0

skrtbhtngr
skrtbhtngr

Reputation: 2251

I think what you want to do is this,

for(i=0;i<MAXPARAMS;i++)
    memset(params[i],'\0',strlen(params[i]));

keeping the length of each string intact.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

Considering the memory allocation is done proerly and it is not freed, I think you need to check the memset() function, if you are targeting the values held the array. Please check the man page here.

Otherwise, if you want to be in the same position as the time of initialization, you can free() the allocated memory and again set the variable as NULL.

Please clarify what do you mean by reset. We'll be able to help out in a batter way then.

Upvotes: 1

Related Questions