Search code examples
cpointerspointer-arithmetic

Printing entered string using pointer manipulation


I am new to pointers, please let me know how can i print the entered character.

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

   int main()
   {
      char *ptr;
      ptr = malloc(32 * sizeof(char));
      *ptr = 'h';
      ptr++;
      *ptr = 'e';
      ptr++; 
      *ptr = 'l';
      ptr++;
      *ptr = 'l';
      ptr++;
      *ptr = 'o';
      ptr++;
      *ptr = '\n';

      printf("value entered is %s\n", ptr);

      return 0;
    }

I want to print hello


Solution

  • You forgot the null-terminator. Add this:

    ptr++;
    *ptr = '\0';
    

    Also, the pointer is now pointing to the null-terminator (or previously the newline character). You have to set it back to point to the 'h' again:

    ptr -= 6;
    

    And when you're done, you should free the memory:

    free(ptr);