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
9
  • 3
    Please don't cast the result of malloc. Commented Aug 28, 2015 at 11:11
  • 2
    Note that sizeof(char) is always 1, so you can replace allocation with ptr = malloc(n + 1);. Commented Aug 28, 2015 at 11:15
  • 2
    @WayneSudo wrong. Since C99 the return value of main() is implicitly 0. Commented Aug 28, 2015 at 11:24
  • 1
    There is no pointer p Commented Aug 28, 2015 at 11:24
  • 1
    Don't cast malloc() and "ptr = (char *) malloc((n + 1)*sizeof(char));" is the same as malloc((n+1) * 1), this is what you need ? Commented Aug 28, 2015 at 11:43

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

He might want to enter spaces and have them count
@MattMcNabb Please see the edit Sir .I tied to cover your point.
Actually, that entire loop should be replaced by fgets(ptr, n + 1, stdin);.
@TheParamagneticCroissant Actually that is right but then also he will have to take care of '\n' .
@ameyCU yes, no question about that! it's just that fgets() makes reading the line simpler.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.