Reputation: 41
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?
Upvotes: 3
Views: 2446
Reputation: 137
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
}
}
Upvotes: 0
Reputation: 223699
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.
Upvotes: 5
Reputation: 1722
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.
Upvotes: 1