Can i use pointer in scanf to take input in an array?
13,518
Solution 1
Absolutely: if a
is an int*
or an array int a[10]
, and i
is between 0 and 9, this expression is valid.
The a+i
expression is the pointer arithmetic equivalent of &a[i]
, which is also a valid expression to pass to scanf
.
Solution 2
yes you can use a+i instead of &a[i],,,, The following code ask you to enter 10 numbers and will save them in an array,,,,and then displays the numbers in it.
check this code :
#include <stdio.h>
int main (void)
{
int a[10], i, j = 0;
for(i = 0; i < 10; ++i ){
printf("Element no %d = ",i);
scanf("%d",a+i);}
printf("Elements in your array are: ");
for(j = 0; j < 10; j++)
printf("%d ",a[j]);
return 0;
}
I hope if this code could help you !!
Related videos on Youtube
Comments
-
Aman Tewary over 1 year
I am trying to do this in c:
scanf("%d",a+i);
where
a
is an array of size10
. Andi
is counter for loop. So is this possible?-
David G over 10 yearsLet's see what you've tried
-
Borgleader over 10 yearsAlso, if you're specifically looking for a C answer, don't tag C++.
-
-
Mats Petersson over 10 yearsAlso works if
a
isint a[10]
or some such - as long asi
is in range, of course. -
gnat about 7 years@Magish why did you edit like that in rev 3? Per my reading user asks a question, see their comment above: "I am gettting segmentation fault in this code" (yes this looks like a blatant not-an-answer and I believe should be flagged as such)