0

Here is the sample of my code. I want to create dynamic character array for storing string.

Here is my code:

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

    int main(void)
    {
      int i , j , n;
      char *ptr;
      printf("enter number of elements \n");
      scanf("%d",&n);
      ptr  = (char *) malloc((n + 1)*sizeof(char));
      for (i = 0;i< n;i++)
      {
        scanf("%c",&ptr[i]);
      }
      for ( i = 0;i <n; i++)
      {
        printf("at %d is %c\n",i,*(ptr + i));
      }
      free(ptr);
    }

But when I try to compile and run this code, no character is assigned to memory which is pointed by pointer p.

Here is the output of my program:

jharvard@appliance (~/c): ./test2
enter number of elements 
8
asdfghjk
at 0 is 
at 1 is a
at 2 is s
at 3 is d
at 4 is f
at 5 is g
at 6 is h
at 7 is j
Tlacenka
  • 520
  • 9
  • 15
Manvendra Singh
  • 586
  • 5
  • 11

1 Answers1

3

Leave a space before %c in scanf-

scanf(" %c",&ptr[i]);

because there will be '\n' left in the buffer after the first scanf forn as you press ENTER after giving value of n.

And you don't need to cast result of malloc.

As what Matt McNabb Sir said in his comment ,for that you can do this -

 scanf("%*c%c",&ptr[i]);

%*c will take care of '\n' and wont even skip if only space is hit.

ameyCU
  • 16,489
  • 2
  • 26
  • 41