C Language Sequencing Error Question

Asked 2 years ago, Updated 2 years ago, 103 views

// C language


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


int main()
{
    int ArrRoom[10] = {0,};

    srand(time(NULL));

    For (inti = 0; i < 10; i++) // Enter a random number from 1 to 10 in the ArrRoom array
    {
        int ran = (rand() % 10) + 1;

        ArrRoom[i] = ran;
    }

    for (inti = 0; sizeof(ArrRoom)/sizeof(int)-1; i++) // order theorem
    {
        int change = 0; // value storage variable 

        if (ArrRoom[i] > ArrRoom[i+1])
        {
            change = ArrRoom[i+1];
            ArrRoom[i+1] = ArrRoom[i];
            ArrRoom[i] = change;
        }
    }

    for (inti = 0; sizeof(ArrRoom)/sizeof(int); i++) // execution result output
    {
        printf("%d ",ArrRoom[i]);
    }

    return 0;
}


I receive random numbers from 1 to 10 and try to sort them in order, but when I run it, the error "Segmentation fault (core dumped)" appears, but I don't know why it comes out like this.

c segmentation-fault

2022-09-22 11:58

1 Answers

Look again at the for grammar. Also, use #define for constants.

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

#define COUNT 10 

int main()
{
    int ArrRoom[COUNT] = {0,};

    srand(time(NULL));

    For (inti = 0; i < COUNT; i++) // Enter a random number from 1 to 10 in the ArrRoom array
    {
        int ran = (rand() % COUNT) + 1;

        ArrRoom[i] = ran;
    }

    for (inti = 0; i < sizeof(ArrRoom)/sizeof(int); i++) // order theorem
    {
        int change = 0; // value storage variable 

        if (ArrRoom[i] > ArrRoom[i+1])
        {
            change = ArrRoom[i+1];
            ArrRoom[i+1] = ArrRoom[i];
            ArrRoom[i] = change;
        }
    }

    For (inti = 0; i < sizeof(ArrRoom)/sizeof(int); i++) // execution result output
    {
        printf("%d ",ArrRoom[i]);
    }

    return 0;
}


2022-09-22 11:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.