×

# weird behaviour of scanf

 0 #include #include 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

 0 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 & please format and repost so that it is easy to analyse for us viewers,, not sure about your question,, good day!!! answered 30 Apr '14, 11:41 -7 accept rate: 0% 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 (01 May '14, 00:56)
 0 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 :) Best, Bruno answered 30 Apr '14, 13:29 3★kuruma 17.7k●72●143●209 accept rate: 8%
 0 array(&a[0],n); i think is wrong you should write array(a,n);...... because arrays are pointers Thank you. answered 01 May '14, 13:37 1★fahd_511 1 accept rate: 0%
 0 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("\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++; } }  answered 02 May '14, 14:36 96●1●4 accept rate: 6%
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×62

question asked: 30 Apr '14, 11:25

question was seen: 930 times

last updated: 02 May '14, 14:37