Search code examples
cstringloopsexecution

String length prints weird numbers. Where is the issue in my code?


My task is: Write a program that calculates the length of a string without using the library

This is my answer, but there is a problem with execution. The length doesnt show properly ! the execution shows length as 107 or 127 for any string I insert.

#include <stdio.h>
#include <stdlib.h>

int main()
{
   //Declaration of variables :
   char ch[50+1];
   int length, i;

   //data :
   printf("ch : ");
   scanf("%s", &ch);
   printf("\n");

   //Search length of string :
   i = 0;
   do
   {
       if(ch[i] == '\0')
       {
           length = i;
       }
       else
       {
           i++;
       }
   }
   while(ch[i] != '\0');

   //Result "
   printf("length pf %s is : %d \n", ch, length);

   return 0;
} ```

Solution

  • There is a problem with the algorithm of the do-while loop.

    The counter i increments short before the condition check.

    If '\0' is found in the next array element (Note, that i is incremented) the loop breaks immediately and won´t be able to set length to i at the next iteration (because there is no next iteration).

    Since length is not initialized, the program has undefined behavior.

    Change:

    do
    {
       if (ch[i] == '\0')
       {
           length = i;
       }
       else
       {
           i++;
       }
    }
    while (ch[i] != '\0');
    

    to

    while (ch[i] != '\0') i++;
    
    length = i;
    

    or even simpler:

    while (ch[i] != '\0') length++;
    

    and omit the counter i, but you need to initialize length by 0 then.


    Side Notes:

    1. Change scanf("%s", &ch); to scanf("%s", ch);. - ch decays to a pointer to its first element.

    2. Use a length modifier at scanf() -> scanf("%50s", ch); to ensure that no buffer overflow occurs when the user inputs a string longer than 50 characters.

    3. Always check the return value of scanf() if an error occurred at consuming input.

    4. Never ignore at the compiler warnings. For scanf("%50s", ch); the compiler should have raised a warning.