【问题标题】:C program: why the program asks the user to enter extra index (asks to enter one more index)?C 程序:为什么程序要求用户输入额外的索引(要求再输入一个索引)?
【发布时间】:2021-03-11 06:09:55
【问题描述】:

程序应要求用户输入数组的长度和单元格的值。

为什么用户需要输入比我在条件中写的多 1 个数字?

int main()
{
    int length, i, *p;
    
    printf("\n Please enter the length of the array: \n");
    scanf("%d", &length);   
    
    p = (int*)malloc(length*sizeof(int));
    
    printf("\n Please enter %d values: \n", length);
    
    for(i=0; i<length; i++){
            
                scanf("\n %d \n", &p[i]);
            
                if(i==0){
            
                    *(p+p[i]) = p[i];
                }else{
                    *(p+p[i]) += p[i];
                }
            
                 
    }

【问题讨论】:

  • *(p+p[i]) 这是要做什么?为什么要将p[i] 添加到p 以形成新指针?另外,请提供准确的运行日志——即显示准确的输入和结果。

标签: arrays c input malloc scanf


【解决方案1】:

您需要更改第二条扫描线。

scanf("\n %d \n", &p[i]); /* Replace this line */
scanf("\n %d", &p[i]); /* By this one */

【讨论】:

    猜你喜欢
    • 2017-03-08
    • 2015-04-07
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 2017-07-16
    相关资源
    最近更新 更多