Array Pointers in C - c

Ok, so I'm learning pointers and I am having trouble understanding how the pointers function in arrays.
Basically given this:
int a[5] = {1,2,4,7,7}; // (allocated at 0xA000)
int b[5] = {4,3,5,1,8}; // (at 0xA0020)
short *c[2]; // (at 0xA0040)
c[0] = (short *)b;
c[1] = (short *)a;
I'm supposed to determine the values of these calculations.
c[0] + 4
To my understanding c is an array of pointers. c[0] is a short that holds the pointer to the first element of the array b. If b starts at 0xA0020 why is is that c[0] + 4 is not 0xA0024 and instead it is 0xA0028.
Also, how am I supposed to determine the value of c[1][2]. c is not a multidimensional array, so how would this calculation work out?
Thank you!

Actually, when you add a number to a pointer, this number is multiplied by the size of the element being pointed to (short in your case because you have a short*). The size of short is probably 2 bytes on your computer, hence it adds 4*2 to the address, which is 8.
Here is a link from MSDN that explains this concept:
Click Here

To my understanding c is an array of pointers.
Correct, to be precise: array of pointers to short
C[0] is a short that holds the pointer to the first element of the array b. If B starts at 0xA0020 why is is that c[0] + 4 is not 0xA0024 and instead it is A0028.
Nope, C[0] is a pointer to short. short size is 2 bytes. When you add an integer to pointer, you're adding its pointed type. In this case, since C[0] is a pointer to short, C[0] + 4 means C[0] + 4 * 2 in bytes. So, if C[0] points to 0xA0020, C[0] + 4 will point to 0xA0028.
Also, how am I supposed to determine the value of c[1][2]. C is not a multidimensional array, so how would this calculation work out?
Pointer semantic in C enables you to treat pointer as array. Provided this declaration:
int* X;
Then these equation applies:
*X == X[0]
*(X + 1) == X[1]
or in general:
*(X + n) == X[n]
where n is an integer value.
Your C is an array of pointers, so first dimension would list the pointers, and second dimension is the data pointed by pointer in the first dimension. Use above equation to find the answer to your question.
NOTE: One thing you have to be aware of is the endianness of the machine. Little endian and big endian stores values bigger than a byte (short, long, int, long long, etc.) in different byte order.

This is because the size of a short integer is 2 bytes.
When you do c[0] +4, you're saying,
"move forward 4 full spaces from c", where a 'space' is the size of the type c points to (a short, so 2 bytes).
If c were a char*, the result WOULD be A0024 (because a char is 1 byte in size). If it were a long, you'd get A0030 or even more instead-- and so on.

c[0] isn't a short that holds a pointer. But rather it's a pointer to a short. And the increment is based on size of what it points to. Which it looks like others have just explained.

In your case c[1][2] gives you a following:
"c" - array of pointers to short (as per declaration in you code)
[1] - gives a second element of array of pointers "c" (pointer to array of integers a)
[2] - gives a data (short) at offset of sizeof(short)*2 from the address of element 2 of array "c" (from start of array "a")
So it will be a one half of second element of array "a". What part you get depends on endianness of your machine.
If you have little endian - then you get a 16 lsb bits of second element of "a". It is 0x0002 in hex, or just "2"

(short *)b; is strictly speaking undefined behavior, anything can happen. So the correct answer to what c[0]+4 holds is anything.
Also, even though a specific compiler may implement this undefined behavior in a particular deterministic way, there would still be no way to tell with the information given. To answer, you would have to know the size of int and short, as well as the endianess of the particular machine.

Related

Why is this int not taking up two bytes of my array? [duplicate]

This question already has answers here:
Data Type Truncation
(2 answers)
Closed 3 years ago.
So basically I am really confused as to why when I assign some value of an array to an int is it not taking up two indices within that array.
I have tried to change my code to use pointers/addresses instead of directly setting the array spot to the int, but none of those fix my problem/confusion.
I have declared my array in my header .h file like this
char arr[4096] = {'\0'};
Then I assign some value of this array to 16.
arr[0]=16;
Then I test to see how much space in the array 16 (an int) has taken up:
p = 0;
while(arr[p]!='\0'){
printf("testing\n");
p++;
}
printf("%d\n",p);
However, it always prints 1 for the value of p instead of 2, indicating that only arr[0] is occupied by the int. I am so confused as to how this memory stuff works and how can I get an int to take up two spots of an array in memory. Why is the value 1 instead of 2? And why does the int only take up 1 spot of the array?
Assigning a value of type int to a member of a char array does not take up multiple elements of the array. Section 6.5.16.1p2 of the C standard regarding the assignment operator = states:
In simple assignment(=), the value of the right operand is
converted to the type of the assignment expression and
replaces the value stored in the object designated by the
left operand.
So the int value is converted to type char before assignment. And because the value 16 falls in the range of possible values for a char, no conversion of the value needs to take place.
If you really want to assign to multiple values of a char array like this, the proper way would be to assign the int value to an int variable and use memcpy:
int value = 16;
memcpy(&arr[0], &value, sizeof(value));
But even then the result would not be any different. Assuming an int is 4 bytes the contents of value are 0x00000010, so only one of the 4 bytes that make up this value contains a value other than 0.
Because 16 is cast down to char and it is placed only in the first cell. This is a reason why you always have 1.
If you try to set 16 as a pattern for few elements, eg:
memset(&arr[0], 16, 4);
or set bigger value (i have 4 bytes int)
*(int*)arr = 0xFFFFFFFF;
then you have got 4 spaces different than '\0'.
When you assign a value to a variable, the value will first be converted to the type of the value. That's just the way C (and basically all other languages) work.
Another thing that might (depending on architecture) the result is that 16 is small enough to fit in one byte. So even if your code were writing to both arr[0] and arr[1] it's not strange if it wrote 16 to arr[0] and 0 to arr[1]. So you should use larger numbers in order to be sure to detect something like this.
In order to achieve what you expect, you can do something like this:
int *p = (int*) &arr[0];
*p = 12345;
But unless you really know what you're doing, you should not do stuff like that. It's very tricky to get it right.
Also, the usual size for int is 4 and not 2.

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

Why address of i+2 is not 653064?

I'm learning pointers in C. I'm having confusion in Pointer arithmetic. Have a look at below program :
#include<stdio.h>
int main()
{
int a[] = 2,3,4,5,6;
int *i=a;
printf("value of i = %d\n", i); ( *just for the sake of simplicity I have use %d* )
printf("value of i+2 = %d\n", i+2);
return 0;
}
My question is if value of i is 653000 then why the value of i+2 is 653008 As far as I know every bit in memory has its address specified then according to this value of i+2 should be 653064 because 1 byte = 8 bit. Why pointer arithmetic is scaled with byte why not with bit?
THANKS in advance and sorry for my bad English!
As far as I know every bit in memory has its address specified
Wrong.
Why pointer arithmetic is scaled with byte why not with bit?
The byte is the minimal addressable unit of storage on a computer, not the bit. Addresses refer to bytes - you cannot create a pointer that points to a specific bit in memory1.
Addresses refer to *bytes*
|
|
v _______________
0x1000 |_|_|_|_|_|_|_|_| \
0x1001 |_|_|_|_|_|_|_|_| > Each row is one byte
0x1002 |_|_|_|_|_|_|_|_| /
\_______ _______/
v
Each column is one bit
As others have explained, this is basic pointer arithmetic in action. When you add n to a pointer *p, you're adding n elements, not n bytes. You're effectively adding n * sizeof(*p) bytes to the pointer's address.
1 - without using architecture-specific tricks like Bit-banding on ARM, as myaut pointed out
You should read about the pointer arithmetic.link given in the comment.
While incrementing the position of pointer , that will incremented based on the data type of that pointer.In this case i+2 will increment the byte into
eight bytes.
Integer is four bytes.(system defined). So i+2 will act as i+(2*sizeof(int)). So it will became i+8. So the answer is incremented by eight.
Addresses are calculating by the byte. Not the bit. Take a character pointer. Each byte having the 255 bits.
Consider the string like this. `"hi". It will stored like this.
h i
1001 1002
Ascii value of h is 104. It will be stored in one byte. signed character we can store positive in 0 to 127. So storing the one value we need the one byte in character dataype. Using the bits we cannot store the only value. so the pointer arithmetic is based on bytes.
When you do PTR + n then simple maths will be like
PTR + Sizeof(PTR)*n.
Here size of integer pointer is 4 Byte.

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