2

I have a char x[16] that I have not initialized, I need to test if something is assigned tox or is it how it is created in the run time. how can I do it? Thank you

example code

int main(int argc, char** argv) {
char x[16];

 //<other part of the code>
if(x is an empty char array (not assigned anything) then skip the next line) {
 //blank
}else {
//<rest of the code>
}
return 0;}

PS: I tried memchar(x, '\0', strlen(x)), if(x[0] == '\0') and if(!x[0]) but it doesn't work as I want since char array does not contain \0 by default.

johan
  • 1,943
  • 10
  • 31
  • 43

2 Answers2

3

You must initialize it like this:

char x[16] = { 0 }; // note the use of the initializer, it sets the first character to 0, which is all we need to test for initialization.

if (x[0] == 0)
  // x is uninitialized.
else
  // x has been initialized

Another alternative, if it is available for your platform, is alloca, which allocates data for you on the stack. You would use it like such:

char *x = NULL;

if (x == NULL)
    x = alloca(16);
else 
    // x is initialized already.

Because alloca allocates on the stack, you don't need to free the data you allocate, giving it a distinct advantage over malloc

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
1

Initializing variables is a good practice, and you can use the compiler to warn you when they are not. Using gcc, you would use the -Wuninitialized flag.

You can initialize your array at compile-time by changing your character array variable like this

char x[16] = {0};

and then test to see

if ('\0' != x[0])
{
   <do something>; 
}
else
{  
   <initialize character string>;
}
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131