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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Nice, but that initialization causes all the elements to be initialized to 0, not the first character as your comment states.
@cnicutar true, but I don't see much of a problem with that considering the OP's question.
alloca is very cool, but it must be used carefully. See stackoverflow.com/q/1018853/417934 for a discussion.
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>;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.