Finding the difference between the addresses of elements in an array - c

I have an exam revision question on pointer arithmetic and one part where we are subtracting the address of two array variables is not making sense to me.
Well one array actually equals the other. I understand the individual outputs
for each array variable and in this case the difference between the two addresses
is 16, given an int = 4 bytes on this os.
What I don't understand is why the subtraction gives 4.
My logic would be that they are 4 positions apart in the array, but this doesn't make sense to me.
int main(void)
{
int oddNums[5] = {1, 3, 5, 7, 9};
int *ip = oddNums;
printf("&oddNums[4] %d - ip %d= %d\n",&oddNums[4], ip, &oddNums[4] - ip);
/*prints &oddNums[4] 2686740 - ip 2686724= 4*/
return EXIT_SUCCESS;
}

Subtraction returns 4 because it returns its result in terms of sizeof(<array-element>). This is done to make subtraction an inverse of addition, which also operates in terms of array element size.
Recall that if a is an array and i is an integer, then a+i is the same as &a[i], so the addition must consider the size of the element. In order to follow the rules of the math, the subtraction must divide out the size of an element as well.
This makes pointer arithmetics a lot easier, because the operations of addition and subtraction take care of dealing with the size of array element. Without this rule, one would need to keep dividing or multiplying results of addition or subtraction by the size of an element in order to get the address of the desired element or to get the offset. This is error-prone, and it is also hard to read. Finally, this would create maintenance nightmare in situations when you change element size from one byte to several bytes, and whoever coded the algorithm has forgotten to multiply or divide by sizeof.

The definition of pointer subtraction is to give the number of elements' difference between the two pointers.
It's similar to adding a pointer to an integer: it means to advance the pointer by that number of elements.
Make sure you are thinking of "pointer" as something that tells you where to find an object of a certain type. (As opposed to thinking of it as an integer representing a memory address).

Related

How exactly array type is stored in C?

So I've been reading Brian W. Kernighan and Dennis M. Ritchie's "The C Programming Language" and everything was clear until I got to the array-to-pointer section. The first thing we can read is that by definition, a[i] is converted by C to *(a+i). Okay, this is clear and logical. The next thing is that when we pass an array as a function parameter, you actually pass the pointer to the first element in that array. Then we find out that we can add integers to such a pointer and even it is valid to have a pointer to the first element after the array. But then it's written that we can subtract pointers only in the same array.
So how does C 'know' if these two pointers point to the same array? Is there some metainformation associated with the array? Or does it just mean that this is undefined behavior and compiler won't even generate a warning? Is array stored in memory as just ordinary values of the size of an array type, one after another, or is there something else?
One reason the C standard only defines subtraction for two pointers if they are in the same array is that some (mostly old) C implementations use a form of addressing in which an address consists of a base address plus an offset, and different arrays may have different base addresses.
In some machines, a full address in memory may have a base that is a number of segments or other blocks of some sort and an offset that is a number of bytes within the page. This was done because, for example, some early hardware would work with data in 16-bit pieces and was designed to work with 16-bit addresses, but later versions of hardware extending the same architecture would have larger addresses but would still use 16-bit pieces of data in order to keep some compatibility with previous software. So the newer hardware might have a 22-bit address space. Old software using just 16-bit addresses would still behave the same, but newer software could use an additional piece of data to specify different base addresses and thereby access all memory in the 22-bit address space.
In such a system, the combination of a base b and an offset o might refer to memory address 64•b + o. This gives access to the full 22 bits of address space—with b=65535 and o=63, we have 64•b + o = 64•65535 + 63 = 4,194,303 = 222−1.
Observe that many locations in form can be accessed by multiple addresses. For example, b=17, o=40 refers to the same location as b=16, o=104 and as b=15, o=168. Although the formula for making a 22-bit address could have been designed to be 65536•b + o, and that would have given each memory location a unique address, the overlapping formula was used because it gives a programmer flexibility in choosing their base. Recall that these machines were largely designed around using 16-bit pieces of data. With the non-overlapping address scheme, you would have to calculate both the base and the offset whenever doing address arithmetic. With the overlapping address scheme, you can choose a base for an array you are working with, and then doing any address arithmetic requires calculating only with the offset part.
A C implementation for this architecture can easily support arrays up to 65536 arrays by setting one base address for the array and then doing arithmetic only with the offset part. For example, if we have an array A of 1000 int, and it is allocated starting at memory location 78,976 (equal to 1234•64), we can set b to 1234 and index the array with offsets from 0 to 1998 (999•2, since each int is two bytes in this C implementation).
Then, if we have a pointer p pointing to A[125], it is represented with (1234, 250), to point to offset 250 with base 1234. And if q points to A[55], it is represented with (1234, 110). To subtract these pointers, we ignore the base, subtract the offsets, and divide by the size of one element, so the result is (250-110)/2 = 70.
Now, if you have a pointer r pointing to element 13 in some other array B, it is going to have a different base, say 2345. So r would be represented with (2345, 26). Then, to subtract r from p, we need to subtract (2345, 26) from (1234, 250). In this case, you cannot ignore the bases; simply working with the offsets would give (250−26)/2 = 112, but these items are not 112 elements (or 224 bytes) apart.
The compiler could be altered to do the math by subtracting the bases, multiplying by 64, and add that to the difference of the offsets. But then it is doing math to subtract pointers that is completely unnecessary in the intended uses of pointer arithmetic. So the C standard committee decided a compiler should not be required to support this, and the way to specify that is to say that the behavior is not defined when you subtract pointers to elements in different arrays.
... it's written that we can subtract pointers only in the same array.
So how does C 'know' if these two pointers point to the same array?
C does not know that. It is the programmer's responsability to make sure about the limits.
int arr[100];
int *p1 = arr + 30;
int *p2 = arr + 50;
//both p1 and p2 point into arr
p2 - p1; //ok
p1 - p2; //ok
int *p3 = &((int)42); // ignore the C99 compound literal
//p3 does not point into arr
p3 - p1; //nope!

Offset between two array element addresses in C

I have a question asking me to find the offset in bytes between two array element addresses:
double myArray[5][7];
If C stored data in column-major order the offset (in bytes) of &myArray[3][2] from &myArray[0][0] would be:
In column major order, I think elements would be laid out as such:
[0][0] -- [1][0] -- [2][0] -- [3][0] -- ..... -- [3][2]
So in my mind to get the offset in bytes is to count the number of jumps between [0][0] and [3][2] and times that by 8 since it's an array of doubles. However, what's confusing me is that it's asking for the offset using the & operator. Would this somehow change the answer since it's asking between two addresses or is the process still the same? I think it'd be the same but I'm not 100% certain.
If my thinking is correct would this then be 8*15 bytes?
The memory lay out for the 2d array would be a contiguous chunk of memory.(Based on your question)
int x[2][3] = {{0,1,2},{3,4,5}};
That will be layed out in (Your question)
--+--+--+--+--+--+
0| 3| 1| 4|2 |5 |
--+--+--+--+--+--+
But in C this is stored like
--+--+--+--+--+--+
0| 1| 2| 3|4 |5 |
--+--+--+--+--+--+
Now you are absolutely right, that you can consider jumps between [0][0] and [3][2] but there is a better way to do that without thinking about all this, you can be sure that their offset will be their address differences.
You can simply get their addresses and subtract them.
ptrdiff_t ans = &a[3][2]-&a[0][0];(this is basically the gaps between the two elements)
That yields the answer. printf("answer = %td",ans*sizeof(a[0][0]); (One gap = sizeof(a[0][0])) [In your case double]
Or even better way would be to
ptrdiff_t ans = (char*)&a[3][2] - (char*)&a[0][0];//number of bytes between them.
I will explain a bit why char* is important here:
(char*)&a[0][0] and &a[0][0] both contain the same thing value-wise.(this is not general enough)
But it matters in pointer arithmetic. (Interpretation is different).
When not using the cast, the interpretation is of the data type of array elements. That means now it consider the difference in doubles. When you cast it, it spits the result in or difference in char-s.
And why this works? Because all data memory is byte addressable and char is of single bytes.
There is something more to this than expected , first let's see what is an array in C? †
C does not really have multi-dimensional arrays. In C it is realized as an array of arrays. And yes those multidimensional array elements are stored in row-major order.
To clarify a bit more we can look into an example of standard §6.5.2.1
Consider the array object defined by the declaration
int x[3][5];
Here x is a 3 x 5 array of ints; more precisely, x is an array of
three element objects, each of which is an array of five ints. In the
expression x[i], which is equivalent to (*((x)+(i))), x is first
converted to a pointer to the initial array of five ints. Then i is
adjusted according to the type of x, which conceptually entails
multiplying i by the size of the object to which the pointer points,
namely an array of five int objects. The results are added and
indirection is applied to yield an array of five ints. When used in
the expression x[i][j], that array is in turn converted to a pointer
to the first of the ints, so x[i][j] yields an int.
So we can say double myArray[5][7]; here myArray[3][2] and myArray[0][0] are not part of the same array.
Now that we are done here - let's get into something else:
From standard §6.5.6.9
When two pointers are subtracted, both shall point to elements of the
same array object, or one past the last element of the array object;
the result is the difference of the subscripts of the two array
elements.
But here myArray[3] and myArray[0] are denoting two different arrays. And that means myArrayp[3][2] and myArray[0][0] both belong to different arrays. And they are not one past the last element. So the behavior of the subtraction &myArray[3][2] - &myArray[0][0] will not be defined by the standard.
†Eric (Eric Postpischil) pointed out this idea.
In a row-major traversal, the declaration is array[height][width], and the usage is array[row][column]. In row-major, stepping to the next number gives you the next column, unless you exceed the width and "wrap" to the next row. Each row adds width to your index, and each column adds 1, making rows the "major" index.
In order to get the column-major equivalent, you assume the next value is the next row, and when the row exceeds the height, it "wraps" to the next column. This is described by index = column * height + row.
So, for an array array[5][7] of height 5, the index [3][2] yields 2*5 + 3 = 13.
Let's verify with some code. You can get column-major behavior simply by switching the order of the indices.
#include <stdio.h>
int main() {
double array[7][5];
void *root = &array[0][0];
void *addr = &array[2][3];
size_t off = addr - root;
printf("memory offset: %d number offset: %d\n", off, off/sizeof(double));
return 0;
}
Running this program yields an address offset of 104, or 13 doubles.
EDIT: sorry for wrong answer
The Simple Answer
C does not have multidimensional arrays, so we have to interpret double myArray[5][7] as one-dimensional array of one-dimensional arrays. In double myArray[5][7], myArray is an array of 5 elements. Each of those elements is an array of 7 double.
Thus, we can see that myArray[0][0] and myArray[0][1] are both members of myArray[0], and they are adjacent members. Thus, the elements proceed [0][0], [0][1], [0][2], and so on.
When we consider myArray[1], we see it comes after myArray[0]. Since myArray[0] is an array of 7 double, myArray[1] starts 7 double after myArray[0].
Now we can see that myArray[3][2] is 3 arrays (of 7 double) and 2 elements (of double) after myArray[0][0]. If a double is 8 bytes, then this distance is 3•7•8 + 2•8 = 184 bytes.
The Correct Answer
To my surprise, I cannot find text in the C standard that specifies that the size of an array of n elements equals n times the size of one element. Intuitively, it is “obvious”—until we consider that an implementation in an architecture without a flat address space might have some issues that require it to access arrays in complicated ways. Therefore, we do not know what the size of an array of 7 double is, so we cannot calculate how far myArray[3][2] is from myArray[0][0] in general.
I do not know of any C implementations in which the size of an array of n elements is not n times the size of one element, so the calculation will work in all normal C implementations, but I do not see that it is necessarily so according to the C standard.
Calculating the Distance in a Program
It has been suggested the address can be calculated using (char *) &myArray[3][2] - (char *) &myArray[0][0]. Although this is not strictly conforming C, it will work in common C implementations. It works by converting the addresses to pointers to char. Subtracting these two pointers then gives the distance between them in units of char (which are bytes).
Using uintptr_t is another option, but I will omit discussion of it and its caveats as this answer is already too long.
A Wrong Way to Calculate Distance
One might think that &myArray[3][2] is a pointer to double and &myArray[0][0] is a pointer to double, so &myArray[3][2] - &myArray[0][0] is the distance between them, measured in units of double. However, the standard requires that pointers being subtracted must point to elements of the same array object or to one past the last element. (Also, for this purpose, an object can act as an array of one element.) However, myArray[3][2] and myArray[0][0] are not in the same array. myArray[3][2] is in myArray[3], and myArray[0][0] is in myArray[0]. Further, neither of them is an element of myArray, because its elements are arrays, but myArray[3][2] and myArray[0][0] are double, not arrays.
Given this, one might ask how (char *) &myArray[3][2] - (char *) &myArray[0][0] can be expected to work. Isn’t it also subtracting pointers to elements in different arrays? However, character types are special. The C standard says character pointers can be used to access the bytes that represent objects. (Technically, I do not see that the standard says these pointers can be subtracted—it only says that a pointer to an object can be converted to a pointer to a character type and then incremented successively to point to the remaining bytes of an object. However, I think the intent here is for character pointers to the bytes of an object to act as if the bytes of the object were an array.)

Subtle differences in C pointer addresses

What is the difference between:
*((uint32_t*)(p) + 4);
*(uint32_t*)(p+4);
or is there even a difference in the value?
My intuition is that in the later example the value starts at the 4th index of the array that p is pointing at and takes the first 4 bytes starting from index 4. While in the first example it takes one byte every 4 indices. Is this intuition correct?
The p+4 expression computes the address by adding 4*sizeof(*p) bytes to the value of p. If the size of *p is the same as that of uint32_t, there is no difference between the results of these two expressions.
Given that
p is an int pointer
and assuming that int on your system is 32-bit, your two expressions produce the same result.

C program array Position

Why does the following C program return the subtraction of 4 of (a+4) and 1 of (a+1)?
#include<stdio.h>
int main()
{
int a[3][2]={1,2,
5,7,
6,8};
printf("\n%d",(a+4)-(a+1));
return 0;}
Also when i substitute the subtraction operator with addition (a+4)+(a+1), it gives
error: invalid operands to binary + (have ‘int (*)[2]’ and ‘int (*)[2]’)
Note that a is an array and when used by itself degrades to a pointer (i.e. a memory address). This means that (a+4) and (a+1) are also memory addresses. Subtracting memory addresses makes sense because you are calculating the distance between the two addresses. However, adding memory addresses is nonsense.
I am unsure what you want to do here, so I am not able to suggest a solution to fix the problem. Feel free to edit your question with more details so that we can help you further.
I ran your code and got 3 as the difference, which makes sense: a + 4 - (a + 1) = 3.
On the error, I believe that C doesn't let you add two memory addresses as a safeguard. It's totally nonsensical to do so as I pointed out in a previous comment. Subtracting one memory address from another, however, gives you something useful in certain cases (the offset between two locations in memory).
you have a syntax error.
you r using a as an single intiger, but the data type of a is integer array.
so an e.g subtraction would be: a[1][3]-a[0][3] and the value here equals 3.
(for your info the array actually looks like a={1,2,5
7,6,8} it has 3 rows and 2 columns.

C array address confusion

Say we have the following code:
int main(){
int a[3]={1,2,3};
printf(" E: 0x%x\n", a);
printf(" &E[2]: 0x%x\n", &a[2]);
printf("&E[2]-E: 0x%x\n", &a[2] - a);
return 1;
}
When compiled and run the results are follows:
E: 0xbf8231f8
&E[2]: 0xbf823200
&E[2]-E: 0x2
I understand the result of &E[2] which is 8 plus the array's address, since indexed by 2 and of type int (4 bytes on my 32-bit system), but I can't figure out why the last line is 2 instead of 8?
In addition, what type of the last line should be - an integer or an integer pointer?
I wonder if it is the C type system (kinda casting) that make this quirk?
You have to remember what the expression a[2] really means. It is exactly equivalent to *(a+2). So much so, that it is perfectly legal to write 2[a] instead, with identical effect.
For that to work and make sense, pointer arithmetic takes into account the type of the thing pointed at. But that is taken care of behind the scenes. You get to simply use natural offsets into your arrays, and all the details just work out.
The same logic applies to pointer differences, which explains your result of 2.
Under the hood, in your example the index is multiplied by sizeof(int) to get a byte offset which is added to the base address of the array. You expose that detail in your two prints of the addresses.
When subtracting pointers of the same type the result is number of elements and not number of bytes. This is by design so that you can easily index arrays of any type. If you want number of bytes - cast the addresses to char*.
When you increment the pointer by 1 (p+1) then pointer would points to next valid address by adding ( p + sizeof(Type)) bytes to p. (if Type is int then p+sizeof(int))
Similar logic holds good for p-1 also ( of course subtract in this case).
If you just apply those principles here:
In simple terms:
a[2] can be represented as (a+2)
a[2]-a ==> (a+2) - (a) ==> 2
So, behind the scene,
a[2] - a[0]
==> {(a+ (2* sizeof(int)) ) - (a+0) } / sizeof(int)
==> 2 * sizeof(int) / sizeof(int) ==> 2
The line &E[2]-2 is doing pointer subtraction, not integer subtraction. Pointer subtraction (when both pointers point to data of the same type) returns the difference of the addresses in divided by the size of the type they point to. The return value is an int.
To answer your "update" question, once again pointer arithmetic (this time pointer addition) is being performed. It's done this way in C to make it easier to "index" a chunk of contiguous data pointed to by the pointer.
You may be interested in Pointer Arithmetic In C question and answers.
basically, + and - operators take element size into account when used on pointers.
When adding and subtracting pointers in C, you use the size of the data type rather than absolute addresses.
If you have an int pointer and add the number 2 to it, it will advance 2 * sizeof(int). In the same manner, if you subtract two int pointers, you will get the result in units of sizeof(int) rather than the difference of the absolute addresses.
(Having pointers using the size of the data type is quite convenient, so that you for example can simply use p++ instead of having to specify the size of the type every time: p+=sizeof(int).)
Re: "In addtion,what type of the last line should be?An integer,or a integer pointer??"
an integer/number. by the same token that the: Today - April 1 = number. not date
If you want to see the byte difference, you'll have to a type that is 1 byte in size, like this:
printf("&E[2]-E:\t0x%x\n",(char*)(&a[2])-(char*)(&a[0]))

Resources