从用户那里获取信息

0 c

 i tried to take input from user 
 input type is not determined(can be char or int)
 i wanna take input and store in pointer array
 while i doing that job forr each pointer i wanna take place from leap area
 that is using malloc
  but below code doesnot work why??? 

 int main(void)
{
    char *tutar[100][20],temp;
    int i;
    int n;
    i=0;

    while(temp!='x')
    {
        scanf("%c",&temp);
        tutar[i]=malloc(sizeof(int));
        tutar[i]=temp;
        ++i;
    }

    n =i;
    for(i=0;i<=n;++i)
    {
        printf(" %c  ",*tutar[i]);
    }
    printf("\n\n");

   /*for(i=0;i<=n;++i)
   {
        printf("%d",atoi(*tutar[i]));
   }
    */
}
Run Code Online (Sandbox Code Playgroud)

注意; 当重写(编辑)以前的邮件时,这个引用有问题,这是一般问题

Pét*_*rök 5

您的代码中存在一些问题,包括:

  • 您声明tutar为字符指针的二维数组,然后将其用作一维数组
  • tutar[i]=temp 将temp(char)的值赋给tutar [i](指向char的指针),有效地覆盖指向新保留的内存块的指针
  • 你没有初始化temp,所以它会有垃圾值 - 偶尔它可能有x你的循环不会执行的值

这是一个改进版本(它没有经过测试,我并不认为它是完美的):

int main(void)
{
    char *tutar[100], temp = 0;
    int i = 0;
    int n;

    while(temp!='x')
    {
        scanf("%c",&temp);
        tutar[i]=malloc(sizeof(char));
        *tutar[i]=temp;
        ++i;
    }

    n =i;
    for(i=0;i<=n;++i)
    {
        printf(" %c  ",*tutar[i]);
    }
    printf("\n\n");
}
Run Code Online (Sandbox Code Playgroud)

请注意,除非您确实需要动态分配内存,否则最好使用简单的字符数组:

    char tutar[100], ...
    ...

    while(temp!='x')
    {
        scanf("%c",&temp);
        tutar[i++]=temp;
    }
    ...
Run Code Online (Sandbox Code Playgroud)

为简洁起见,我i在赋值语句中递增.