cpointers

printf not printing out the given parameters


The code is supposed to print out 13:Hello World!, but the output is only 13:.

#include <stdio.h>
   int main(){

  char *str = "Hello World!\n";

 int Laenge= 0;

  while (*str++){

   ++Laenge;
   }  
  printf(" %d:%c\n", Laenge, *str);
  return 0;
   }

Solution

  • Your code is not working because your are incrementing the pointer str until the null terminator is found, +1 because of the post increment, leaving it pointing out of bounds of the string literal.

    Dereferencing it with *str after the loop makes the program have undefined behavior since it's pointing out of bounds.

    Since you are using the conversion specifier %c to print only one character, printing the full string was never going to work. Use %s to print the string.

    Only increment the counter Laenge until you find the null character:

    #include <stddef.h>  // size_t
    #include <stdio.h>
    #include <string.h>  // strlen (used for confirmation)
    
    int main(void) {
        char *str = "Hello World!\n";
    
        size_t Laenge = 0;
    
        while (str[Laenge]) {
            ++Laenge;
        }
    
        printf("%zu:%s\n"                                 // "13:Hello World!\n\n"
               "strlen=%zu\n", Laenge, str, strlen(str)); // "13\n"
    }