Search code examples
cstringdynamic-memory-allocation

i have written this code and but it's not working properly


I am writing a code that accepts a string of length as much a user want and displays it.so this is what I have written

#include<stdio.h>
#include<stdlib.h>
void main()
{
  char *a;
  int i,n;
  a=(char*)calloc(1,sizeof(char));
  printf("enter the string\t");
  for(i=0;a[i]!=0;i++)
  {
        scanf("%[^0]c",&a[i]);
        n=2+i;
        a=(char*)realloc(a,(n)*sizeof(char));
  }
  for(i=0;a[i]!=0;i++)
  {
        printf("%c",a[i]);
  }
  free(a);
  a=NULL;
}

but it's not entering into the loop and accepts any input. can you tell me what's going wrong? THANKS


Solution

  • You are not entering the loop because you allocated a with calloc, so a[0] is 0. It will fail the initial a[i]!=0 test of both of your for loops.