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;
}
To reverse an array means to reverse its elements in place.
What you are trying to do is to copy one array into another array in the reversed order. The dynamically allocated array stays unchanged. It is not the same as to reverse an array.
Also it is unclear why one array is allocated dynamically and another array is a variable length array. Using a variable length array in general can be unsafe because there can be not enough memory to allocate it at run-time.
And there is no any need to declare variables i
and j
in the file scope. You should declare variables in minimum scopes where they are used.
And according to the C Standard the function main without parameters shall be declared like
int main( void )
As for your problem then the second argument of this call of scanf
shall be a pointer to an object.
scanf("%d", p[i]);
That is you need to write either
scanf("%d", p + i);
or
scanf("%d", &p[i]);
The code snippet that reverses your dynamically allocated array can look the following way
for ( int i = 0; i < n / 2; i++ )
{
int tmp = p[i];
p[i] = p[n - i - 1];
p[n - i - 1] = tmp;
}
As you can see neither additional array is required.