newbie newbie -4 years ago 79
C Question

Is there any way to create an empty C array, and keep track of its emptyness while updating it?

This wasn't my original question, which was actually not a very smart one, but admin made me modify some of my posts, which I think was a fair thing to ask since I wasn't being very useful here.




Anyway, I'm trying to create an array of void*, so I can also store int* in it.




The idea of this simple program is that it should have an array of pointers to void, and then it can store pointers to int.
In a very lame, and slow way program is supposed (it doesn't) to know if the array is holding pointers to void in every element based in element's size, then it's an empty array; if it holds at least one pointer to an int then it isn't an empty pointer.




/*Mar 21, 2017
*11:01:10 PM
*/

#include <stdio.h>

const char TRUE = 1 ;
const char FALSE = 0 ;

void isArrayEmpty();

int main (void)
{
void* testArray [10] ;
isArrayEmpty(testArray) ;
int randomValues [] = { 5, 7, -15, 9000, 4555, 89, 20000, 45000, 0, -666, 777 } ;
for ( int i = 0 ; i < 10 ; i++ ){
testArray [i] = &randomValues[i] ;
}
isArrayEmpty (testArray) ;
return 0 ;
}
void isArrayEmpty(void* array[]){

char isEmpty = TRUE ;
for ( int i = 0 ; i < 10 ; i++ ){
if ( sizeof( array[i] ) != sizeof(void*) ){
isEmpty = FALSE ;
printf("%s\n", "Array is not empty!") ;
break ;
}
}
if ( isEmpty ){
printf("%s\n", "Array is empty, biatch!") ;
}

}





I tried that but it says is empty! any thoughts?

Answer Source

If an array is uninitialized, then there is no way that your program can determine that just based on the array. You would need to "remember" that information yourself, e.g.:

#include <stdbool.h>

int main (void)
{
    int a[3] ;
    bool a_empty = true;

    // ...
    if ( a_empty )
        printf("a is empty");
    // ...

    a[0] = 1; 
    a_empty = false;
}

Another approach would be to define a particular set of contents as representing "empty" (this is called sentinel values):

#include <stdbool.h>

enum { EMPTY = -1 };

bool is_empty(int a[3])
{
    return a[0] == EMPTY && a[1] == a[0] && a[2] == a[0];
}

int main (void)
{
    int a[3] = { EMPTY, EMPTY, EMPTY };

    // ...
   if ( is_empty(a) )
        printf("a is empty");
}

Of course you would have to choose sentinels that are not valid data for the expected array contents. If no such sentinels exist then you have no choice but to use the extra variable as in my first example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download