4

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?

5
  • 1
    Let's see what you've tried Commented Aug 25, 2013 at 18:55
  • 6
    Also, if you're specifically looking for a C answer, don't tag C++. Commented Aug 25, 2013 at 18:56
  • so long as a+i results in a valid writable address for storing an int, can you think of a reason this would not work ? Commented Aug 25, 2013 at 18:58
  • well i am trying to insert an element in an integer array. I have never done it this way. so it would be nice to know how to do it. Anyways, there is no compile time error but there is some logical error as after taking input in an array from the user, I am not able to insert other elements using this. And I am passing the base of an array to another function and using pointer in it to insert the elements. Commented Aug 25, 2013 at 19:00
  • Well if you've never done it this way and you're working in C++ why gain a bad habit? Use C++ streams. Commented Aug 25, 2013 at 19:01

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Also works if a is int a[10] or some such - as long as i is in range, of course.
1

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

Comments

-2

Try this solution:

#include <stdio.h>

int main (void)
{
  int *p, i, j = 0, n;
  printf("enter the value of n ");
  scanf("%d",&n);
  for(i = 0; i < n; ++i ){
    scanf("%d",p+i);}

  printf("Elements in your array are: ");

  for(j = 0; j < 10; j++)
    printf("%d  ",*(p+i));
  return 0;
}

1 Comment

@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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.