简体   繁体   中英

WHY I GET SEGEMENT FAULT ERROR IN C LANGUAGE WHEN I USE 1-D ARRAY

#include <stdio.h>

int main()
{
    //Initialize array

    int n; // n is use to decide the size of array 
    int x[n];
    int y[n];
    printf("enter the size of array:");
    scanf("%d", &n);

    if (n > 0)
    {
        for (int i = 0; i < n; i++)
        {
            printf("enter elements : \n");
            scanf("%d", &x[i]);
        }
    }

    printf("Array in reverse order: \n");
    //Loop through the array in reverse order
    for (int i = n - 1, j = 0; i >= 0; i--, j++)
    {
        y[j] = x[i];
        printf("%d ", y[j]);
    }

    return 0;
}

Above program, I have created a array which size can be decided by user And also user can put elements in it So after that I want to reverse this array and want to store in another array But got this error again and again I have tried codeblock with gcc compiler But here I got different problem, my program get wired So anyone can help me to understand this problem I am a beginner in coding

When the x and y arrays are created, n is uninitialized. There's no knowing how large these arrays will be. You loops are almost certainly accessing the array out of bounds.

You want to read n , then create the arrays. Of course you also want to error check the result of scanf .

    int n; // n is use to decide the size of array 

    printf("enter the size of array:");
    scanf("%d", &n);

    int x[n];
    int y[n];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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