How do we know that a string element in C is not initialized?

Is there a way to find out if an element in a string in C has a value or not? I tried using NULL, `` and '', but they don't seem to work. I need to shift characters 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;

}

+3
source share
7 answers

No. Since it literalhas automatic storage, its elements will not be initialized; the values ​​in the array are undefined.

You can initialize each element with something special and test it. for example you can change

char literal[100];

char literal[100] = {0};

to initialize each element to 0. You will need to change the while loop completion check to

while(index < 100) {
  if(literal[index] == 0) 
         printf("Empty"); 
   ...
  }
}

, , 0 , " ".

+6

, . , - , . .

+3

C . - , , , . , "unset" .

+1

, , . , , " " .

+1

0 () '\ 0' - C ,

Try

memset(&literal, 0, 100);

, 99 '\ 0'

+1

c - , '\0' . ( ).

, , , .

, , , . .

0

, undefined , , , ASCII, . - for calloc, , 0.

for (i = 0; i < 100; i++) literal[i] = '\0';

OR

char *literalPtr = (char*)calloc(100, sizeof(char)); // Array of 99 elements plus 1 for '\0'

There is no guarantee. Therefore, it will be classified as undefined behavior, since it depends on the compiler implementation and execution.

Hope this helps, Regards, Tom.

0
source

Source: https://habr.com/ru/post/1730771/


All Articles