3

I have a char array where some indices have chars but some are uninitialized. I want to do an operation only on the ones that have values but when I try strcmp with "" it doesn't work since they are initialized with junk values, and aren't empty. How can I check this?

3 Answers 3

5

There is no such thing as an "empty" value for a variable, and therefore there is no way to determine whether an array element (or any variable) is initialized or not just by looking at it. An object that is uninitialized has an indeterminate value. Attempting to read it could yield any value, and in fact could invoke undefined behavior in some cases.

The way to handle this is to keep track of which array elements have been written to in some way.

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

Comments

1

You can't check by definition something that is uninitialized in C. The uninitialized variable does not have a defined value so any value in that char array could be uninitialized and may be different every time you run your program depending on your environment and compiler.

A simple solution is to initialize the array to something before doing any operations on it. It sounds like based on your example initializing them to the null terminator would be best, but you could do any character that you could later identify.

Comments

0

You can do something like:

char a[100];
memset(a, 0, sizeof(a)); // initialize all fields with '\0'

// fill the array with some chars

strcpy(a, "blah");
strcpy(a + 10, "hoho");

// check for empty ((unsigned char ) *(a + i) == 0)

int i = 0;
for(i = 0; i < sizeof(a); i++)
{
   if(a[i] == 0)
   {
      // do your thing here
   }
}

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.