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 !!

Share:
13,518

Related videos on Youtube

Aman Tewary
Author by

Aman Tewary

Ninja

Updated on September 15, 2022

Comments

  • Aman Tewary
    Aman Tewary over 1 year

    I am trying to do this in :

    scanf("%d",a+i);
    

    where a is an array of size 10. And i is counter for loop. So is this possible?

    • David G
      David G over 10 years
      Let's see what you've tried
    • Borgleader
      Borgleader over 10 years
      Also, if you're specifically looking for a C answer, don't tag C++.
  • Mats Petersson
    Mats Petersson over 10 years
    Also works if a is int a[10] or some such - as long as i is in range, of course.
  • gnat
    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)