int main()
{
int n,a[20];
printf("Enter the size of the array");
scanf("%d",&n);
array(&a[0],n);
}
void array(int *j,int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\n Enter the elements of array");
scanf("%d",j);
j++;
}
printf("The elements of array are");
for(i=0;i<n;i++)
{
printf("\n%d",*(j));
j++;
}
}
IN #scanf# IF IN PLACE OF THAT I AM DOING THIS THEN THE CODE IS SUCCESSFULLY EXECUTING.
CAN ANYONE EXPLAINN ME WHY??
though both means same…
Since j is a pointer to an array, it means that j holds the first value in the array.
This means that incrementing it will produce the same effect as that of iterating trough the array elements, i.e., if *j is the first element of the array, then, doing j++, or, as you wrote in your code j+i, will change the pointer’s location to point to the ith element in the array, and, as such, both notations will produce the same effect
from that location. To make the same code print the array values correctly, either change the scanf argument to
a + i
or make the following change:
void array(int *j,int n)
{
int i;
int *k = j;
for(i=0;i < n;i++)
{
printf("\n Enter the elements of array");
scanf("%d",j);
j++;
}
j = k;
printf("The elements of array are");
for(i=0;i < n;i++)
{
printf("\n%d",*(j));
j++;
}
}