我已经写了这段代码,但它不能正常工作

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

我正在编写一个代码,它接受用户想要的长度的字符串并显示 it.so 这就是我写的

#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;
}

但它没有进入循环并接受任何输入。你能告诉我出了什么问题吗?谢谢

您没有进入循环,因为您将 a 分配给了 calloc,因此 a[0] 为 0。它将无法通过您的两个初始 a[i]!=0 测试for 循环。