I need to input two 1-D arrays Array1 and Array2. And want them to swap elements using pointers. I am using that temp variable method with pointers. This is what I have been doing:
#include <stdio.h>
int main()
{
int a[100],b[100],*temp;
int n,i;
int *p=a;
int *q=b;
printf("Enter size of array1&2:");
scanf("%d",&n);
printf("Enter array1&2 elements:");
for(i=0;i<n;i ){
printf("Enter array1 element [%d]:",i);
scanf("%d",p i);
printf("Enter array2 element [%d]:",i);
scanf("%d",q i);
*temp=*(p i);
*(p i)=*(q i);
*(q i)=*temp;
}
printf("Array1 elements: ");
for (i=0;i<n;i ){
printf("%d/n",*p i);
}
printf("Array2 elements: ");
for (i=0;i<n;i ){
printf("%d\n",*q i);
}
}
But after entering 1 value for each array, the output crashes. Where am I messing up?
CodePudding user response:
Declare the variable temp
as having the type int
instead of int *
.
int a[100],b[100],temp;
and then write
temp = *(p i);
*(p i) = *(q i);
*(q i) = temp;
Otherwise you are trying to dereference the uninitialized pointer temp
with an indeterminate value that invokes undefined behavior.
Also in the calls of printf
you are incorrectly using the pointer arithmetic.
For example instead of
printf("%d/n",*p i);
write
printf("%d/n",*( p i ));
Otherwise you are outputting the value of the first element of the array plus the value of i
.