У меня проблема с домашней работой, когда я должен ввести массив и извлечь из него все отдельные элементы.

Для этого я создал новый 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++;
        }
    }

Как бы то ни было, моя программа все еще не работает.

0
Swarnim Khosla 19 Авг 2019 в 16:23

2 ответа

Лучший ответ

В следующей части вашего кода:

 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++;. Ваш цикл сканирования правильный.

1
mik1904 19 Авг 2019 в 13:43

В вашей программе есть две ошибки.

Во-первых, внутри цикла while переменная i не увеличивается.

Напишите цикл как

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

Во-вторых, вы забыли скопировать элементы из массива в sub_array.

Включить этот цикл

for ( i = 0, j = 0; i < number; i++ )
{

    if ( *( array + i ) != 0 ) *( sub_array + j++ ) = *( array + i );
}

Перед печатью sub_array.

И вы должны освободить всю выделенную память.

free( sub_array );
free( array );
1
Vlad from Moscow 19 Авг 2019 в 14:03