-4

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

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
Ashish Dogra
  • 593
  • 4
  • 13
  • Why are you printing character by character instead of putting this into a NULL-terminated string buffer and just feeding that to `printf` directly? While `free(a)` is understandable, setting `a` to `NULL` is really pointless. – tadman Dec 19 '17 at 18:45
  • Normally you'd tackle this problem by allocating an optimistically large buffer and if the user exceeds that size, reallocate with double the size. This avoids relentless reallocation. – tadman Dec 19 '17 at 18:46
  • Welcome to Stack Overflow! [Please see this discussion on why not to cast the return value of malloc() and family in C..](https://stackoverflow.com/q/605845/2173917) – Sourav Ghosh Dec 19 '17 at 18:46
  • `scanf("%[^0]c",&a[i])` is not a valid format. I suggest you use `fgets` and reallocate in steps of say 100 bytes, and repeat until the `'\n'` newline is detected at the end of the input string. Note that `'\0'` does not terminate input strings, but only C strings. – Weather Vane Dec 19 '17 at 18:53
  • Please don't edit your question from errors pointed out. Rolled back. – Weather Vane Dec 19 '17 at 19:02
  • 1
    @WeatherVane `scanf("%[^0]c",&a[i])` is a valid format, yet certainly not what OP wants. – chux - Reinstate Monica Dec 19 '17 at 19:46
  • @chux yes, I phrased it poorly. – Weather Vane Dec 19 '17 at 20:48

1 Answers1

1

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.

Andrew Cottrell
  • 3,312
  • 3
  • 26
  • 41