1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "npstringarray.h"
int NP_Stringarray::remove_item( const char *item )
{
if ( mutex )
return 3;
mutex = 1;
if ( item == NULL )
{
strcpy( error_message, "NP_Stringarray: remove_item(): NULL item"
" pointer passed as argument." );
mutex = 0;
return 1;
}
if ( item_list == NULL || total == 0 )
{
strcpy( error_message, "NP_Stringarray: remove_item(): there are no"
" items currently stored in this object." );
mutex = 0;
return 2;
}
char **pointer = item_list;
int i;
for( i = 0; i < total; ++i )
{
if ( !strcmp( *pointer, item ))
break;
++pointer;
}
if ( i == total )
{
snprintf( error_message, sizeof error_message,
"NP_Stringarray: remove_item(): no such item"
" is stored in this object: %s.", item );
mutex = 0;
return 2;
}
mutex = 0;
return remove_item( i );
}
int NP_Stringarray::remove_item( int i )
{
if ( mutex )
return 3;
mutex = 1;
if ( i >= total || i < 0 )
{
snprintf( error_message, sizeof error_message,
"NP_Stringarray: remove_item(): index out of range: %d.",
i );
mutex = 0;
return 1;
}
if ( total == 1 )
{
if ( item_list != NULL )
{
if ( *item_list != NULL )
free( *item_list );
free( item_list );
item_list = NULL;
}
total = 0;
mutex = 0;
return 0;
}
char **temp_list;
if (( temp_list = ( char **)calloc( total - 1, sizeof *item_list ))
== NULL )
{
perror( "calloc" );
exit( 1 );
}
char **pointer = item_list;
char **temp = temp_list;
for( int j = 0; j < total; ++j )
{
if ( j == i )
{
if ( *pointer != NULL )
free( *pointer );
++pointer;
continue;
}
*temp = *pointer;
++pointer;
++temp;
}
free( item_list );
item_list = temp_list;
--total;
mutex = 0;
return 0;
}
|