首页 > 解决方案 > scanf 不断取值(输入)

问题描述

我有一个作业问题,我必须输入一个数组,并从中取出所有不同的元素。

为此,我创建了一个新的 sub_array ,其中将存储所有不同的值,但是在输入期间scanf没有按应有的值取值?

这是我的代码:-

# include <stdio.h>
# include <stdlib.h>

int main()
{
    int number; // Variable name "number" which will specify the size of dynamically allocated array.

    printf("Enter the size of your array\n");
    scanf("%d",&number);

    int *array;
    array = (int*)calloc(number, sizeof(int)); // Dynamically allocated memory.

    int i,j=0; // Counter variables for loop.

    printf("Enter the elements of arrays\n");

    for(i = 0; i < number; i++)
    {
        scanf("%d",(array + i)); // Code is asking for endless numbers and is not outputting the desired result. THIS IS THE PROBLEM SECTION.
    }


    for(i = 0; i < number; i++)
    {
        for( j = i + 1 ; j < number; j++)
        {
            if( *(array + i ) == *(array + j))
            {
                *(array + j) = 0; // My way of removing those numbers which are the repeated. (Assigning them value of zero).
            }
        }
    }

    i=0;j=0;

    int sub_number = 0;

    while(i < number)
    {
        if(*(array + i) != 0)
        {
            sub_number++; // Variable name "sub_number" which will specify the size of dynamically allocated array "sub_array".
        }
    }

    int *sub_array;
    sub_array = (int*)calloc(sub_number,sizeof(int));

    for(i = 0;i < sub_number;i++)
    {
        printf("%d\n",*(sub_array + i)); // Desired array which only contains distinct and unique variables.
    }
    return 0;
}

编辑:- 我错过了一个循环,我忘记填充 sub_array 循环。这是代码:-

for(i = 0;i < number ;i++) //New code inserted.
    {
        if( *(array + i ) != 0)
        {
            *(sub_array + j) = * (array + i );
            j++;
        }
    }

但是我的程序仍然无法正常工作。

标签: cfor-loopmemory-managementinitializationdynamic-memory-allocation

解决方案


在代码的以下部分:

 while(i < number)
{
    if(*(array + i) != 0)
    {
        sub_number++; // Variable name "sub_number" which will specify the size of dynamically allocated array "sub_array".
    }
}

你没有增加 i。你错过了一个i++;. 你的 scanf 循环是正确的。


推荐阅读