Is there a way to know whether the element in a string in C has a value or not? I have tried using NULL, ”, and ‘ ‘, but they don’t seem to be working. I need to shift the characters down to index 0 without using stdlib functions.
#include <stdio.h>
int main()
{
char literal[100];
//literal[99] = '\0'
literal[98] = 'O';
literal[97] = 'L';
literal[96] = 'L';
literal[95] = 'E';
literal[94] = 'H';
int index = 0;
while(literal[index] != '\0')
{
if(literal[index] == NULL) // does not work
printf("Empty");
else
printf("%c", literal[index]);
++index;
}
getchar();
return 0;
}
No. Since
literalhas automatic storage, its elements will not be initialized, the values in the array is undefined.You could initialize every element to something special and check for that value.
e.g. you could change
to initialize every element to 0.
You’d have to change your while loop termination check to
That might not be optimal if you need to perform more string manipulation on the array though, as 0 now means empty element and also ‘end of string’.