reversing an array created dynamically. code not running properly

reverse the elements of an array that is created dynamically by user inputs. this is the question. I have written a code in C language.

The problem with this code is that it is compiled successfully without an error but does not take input more than 3 integers in vs code. but the online compiler shows segmentation fault just after giving first value as an input to array. Can someone explain where is my fault and how should i correct it?

#include<stdio.h>
#include<stdlib.h>
int i, j;
int main(){
int *p;
    printf("enter the number of elements you want in the array");
    int n; 
    scanf("%d", &n);
    p = (int *)malloc(n * sizeof(int)); //array declared having garbage values
    for (i = 0; i < n; i++){
        printf("the value of %d element is : ", i+1);
        scanf("%d", p[i]);
    }
    for (i = 0; i < n; i++){
        printf("the elements of array are : ");
        printf("%d \n", p[i]);
    } //till here we have just printed an array by taking inputs from user.
    int q[n];
    for(i = 0, j = n-1; i<n; i++, j--){
        q[i]= p[j]; //copying contents from heap array to newly created array.
    }
    for ( i = 0; i < n; i++){
        printf("the reverse elements of array are : %d", q[i]);
    }
    
    free(p);
    return 0;
}


Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation