Pointer to an array Issue in C language

*This Declaration of (p)[n] for Pointer Array(Arrays With a Pointer).

I cannot Scanf Array From User

This Program

#include <stdio.h>

int main()
{
    int i,n;
    scanf("%d",&n);
    int (*a)[n];
    int *p;
    p = *a;
    for(i=0;i<n;i++)
    {
        scanf("%d",(p+i));  // This Shows Segmentation Fault
    }
    for(i=0;i<n;i++)
    {
        printf("%d",*(p+i));
    }

    return 0;
} 

PLEASE REPLY WITH A CORRECT ANSWER .

This statement is not a pointer to an array, it’s an array of pointers and you’re performing array operations like storing & accessing the values. This statement will create n pointers and p will point to that array of pointers.

You can fix it by doing like this,

#include <stdio.h>

int main()
{
    int i,n;
    scanf("%d",&n);
    int x[n];
    //int (*a)[n];
    int *p;
    p = x;
    //p = *a;
    for(i=0;i<n;i++)
    {
        scanf("%d",(p+i)); // This Shows Segmentation Fault* 
    }
    for(i=0;i<n;i++)
    {
        printf("%d",*(p+i));
    }

    return 0;
}

Here, p is a pointer which is pointing to the array - so p will be a pointer to an array.

Thank You.

1 Like