0

I'm doing my C programming on Ubuntu Linux, and was wondering how subtraction between array names works. I have an int array, A, of 10 items, and want to do &A[6] - A. When I do this, my printed value is 6. I thought I would get the item referenced at A[6], then subtract by the item/int at A[0] (A ==> &A[0]). However, I simply get 6.

#include <stdio.h>

int main (void) {
    int A[10] = {1, 1, 1, 1, 1, 1, 23, 1, 1, 1};

    int x = &A[6] - A;

    printf("%d\n", x);

    return 0;

}

-How did it print 6? Do I have to look at the Hex addresses with GDB? Thank you.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
django_moose
  • 355
  • 1
  • 4
  • 10
  • 3
    `&A[6] - A` performs *pointer arithmetic*. (`&A[6]` gives you a `int*`) – UnholySheep Apr 21 '18 at 20:46
  • 1
    maybe you want `A[6] - A[0]` – Jean-François Fabre Apr 21 '18 at 20:49
  • 1
    you need not reference *A[6]* also you need to dereference *A* that means `A[6] - *A` should do what you want. – ytobi Apr 21 '18 at 20:50
  • 1
    Pointer arithmetic considers the size of the type. The difference between the *address* of two array elements, is therefore the same as the difference between the *index* of the two array elements. – Weather Vane Apr 21 '18 at 20:58
  • Sorry for the misunderstanding, I know what &A[int#] returns here, and I am familiar with how to actually extract the values from an int array and perform arithmetic on it. This is just a test question for one of my CS classes and I was having trouble understanding the concept here. Thank you – django_moose Apr 22 '18 at 14:41

0 Answers0