weird behaviour of scanf

pointers

#1

#include<stdio.h>
#include<conio.h>
void array(int * ,int );

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("

Enter the elements of array");
scanf("%d",j);
j++;
}
printf(“The elements of array are”);
for(i=0;i<n;i++)
{
printf("
%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…

scanf("%d",(j+i));
and deleting j++;


#2

hello coder 1901,

I see you are new to programming, couple of mistakes that I spotted

1.void array(int j,int n) -> j should be a int pointer and hence int*

2.scanf("%d",j); add &

  1. please format and repost so that it is easy to analyse for us viewers,

not sure about your question,

good day!!!


#3

Hi,

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 :slight_smile:

Best,

Bruno


#4

array(&a[0],n);
i think is wrong you should write array(a,n);… because arrays are pointers

Thank you.


#5

After the first for loop, j points to index a + n.
The next for loop starts incrementing j 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("
 Enter the elements of array");
            scanf("%d",j);
                        j++;
    }

    j = k;
    printf("The elements of array are");
    for(i=0;i < n;i++)
    {
        printf("
%d",*(j));
                j++;



    }
}

#6

ok, i found it, your j++ has local scope meaning for every iteration of for loop you are going to start off again with &a[0]. Hope this helps


#7

you are increasing j but not shifting back to initial position. Use j+i.