tags:

views:

150

answers:

2

hello i have an char** arr which is an array of strings and i want to erase the 2 last cell of the array or maybe to create a new char** but without those last 2 cells thank you very much.

+1  A: 

Do you know the size of your array?

The code might be like this assuming the length of the array is array_size:

int array_size;
char **array = malloc (sizeof (char*) * array_size); 
....
free (*(array+array_size)); *(array+array_size) = NULL;
free (*(array+array_size-1)); *(array+array_size-1) = NULL;

In case you don't know the length, the fact that the element past last used element is NULL will help.

Then the code somewhat more complex:

for (char** ai = array; *ai != NULL; ai++);
ai--;
free(*ai); *ai = NULL;
ai--;
free(*ai); *ai = NULL;
buratinas
`*(array+array_size)` is past the end of the array.
Marcelo Cantos
thank youi do know the size of the array and i am tryingfor ... size-2 .. strcpy
sagi
+1  A: 

How about you free the memory pointed to by the last two elements in the array, set them to zero and then separately keep track of the sizeof the array.

For example

unsigned int len = 10;
char **aryStr = (char**) malloc(sizeof(char *)*len);
....
free(aryStr[--len])
aryStr[len] = NULL;
free(aryStr[--len])
aryStr[len] = NULL;

You can use the new len as a parameter to routines manipulating the array. Alternatively you create extra value (sentinel) in your array that marks the end of data by pointing to NULL. You process the array (like a string) by iterating over it until you find a NULL value.

BeWarned