简体   繁体   English

接受用户的输入

[英]taking input from user

 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]));
   }
    */
}

note that; 注意; this cite has problem when rewrite(edit) the previous mail it is general problem or not 此引用在重写(编辑)先前的邮件时有问题,这是否是普遍问题

There are several problems in your code, including: 您的代码中存在几个问题,包括:

  • you declare tutar as a two-dimensional array of pointers to character, then use it as a one-dimensional array 您将tutar声明为指向字符的二维数组,然后将其用作一维数组
  • tutar[i]=temp assigns the value of temp (a char) to tutar[i] (a pointer to char), effectively overwriting the pointer to the newly reserved memory block tutar[i]=temp将temp(一个char)的值分配给tutar [i](一个char的指针),有效地覆盖了指向新保留的内存块的指针
  • you don't initialize temp , so it will have garbage value - occasionally it may have the value x , in which your loop will not execute 您没有初始化temp ,因此它将具有垃圾值-有时可能具有值x ,在其中您的循环将不会执行

Here is an improved version (it is not tested, and I don't claim it to be perfect): 这是一个改进的版本(未经测试,并且我不认为它是完美的):

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");
}

Note that unless you really need to allocate memory dynamically, you would be better off using a simple array of chars: 请注意,除非确实需要动态分配内存,否则最好使用简单的char数组:

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

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

For the sake of brevity, I incremented i within the assignment statement. 为了简洁起见,我在赋值语句中增加了i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM