Hey guys Im trying to get down some theoretical stuff for Pointers and Arrays. I was hoping someone could reaffirm some suspicions I had with the concept of pointers and arrays.
Suppose I had something like this
int ia[] = {0,1,2,3,4,5};
ia[2]; // =2
int* ip = &ia[0]; // pointer ip gets the address of element 0 in array ia
ip[2]; // ??
ip[2] = 42; //
Most of this code is theoretical obviously but im a bit unsure of the last 2 lines. First off is saying ip[2] the same as saying ip now points to the 2ndth element in the array? Is it equivalent to saying *ip = ia[2] ?
Im also confused with the last line. ip[2] = 42; so the 2ndth element of the object that the ip points to, that address gets the value 42? Or is that an array notation method of dereferencing? Im just a bit confused on whats going on.
ia[n] is a different way of writing *(ia+n), therefore int* ip = &ia[0] is the same as int *ip = ia.
You are assigning ia to ip. That of course also makes ip[n] == ia[n] for all values of n.
The following creates an array called ia and stores the numbers in curly braces in the array:
int ia[] = {0,1,2,3,4,5};
The following in effect, does nothing:
ia[2];
However, if I take the above statement and change as follows, it assigns the value 2 to the integer t. This is because 2 is the third element in ia, and ia[2] references the third element in ia.
t = ia[2];
If your original declaration of ia had been
int ia[] = {0,1,15,3,4,5};
then you would be assigning t to 15.
The following changes the value at index 2 in ia to 42:
ip[2] = 42;
Now, ia consists of {0,1,42,3,4,5}.
This is because ia[2] is like saying *(ia + 2). If you assign ip to ia, then ip points to the first element of ia.
Similarly, ip[2] is like saying *(ip + 2). So, changing ip[2] will change ia[2], they reference the same chunk of memory.
When you write a[i] it is translated to *(a+i) where a is the base address (basically a pointer)
Also for arrays , base address is same as address of 1st element so address of a[0] is same as a [i.e a = &a[0]]
So, ip[2] = 42; translates to *(ip+2) = 42
Also, * gives value at that address ip[2] = 42 means *(ip+2) = 42 i.e value at location (ip+2)
a[b] is exactly the same as *(a + b). ALWAYS. So ia[2] is equivalent to *(ia + 2), and ip[2] is equivalent to *(ip + 2).
However, it is more subtle than that because ia and ip have very different types. ia is of array type; whereas ip is of pointer type. So they are not "the same" -- they are not even the same type of thing. It's like apples and oranges.
An array expression, used within certain contexts, can be implicitly converted to a pointer to its first element. If you wrote, int *ip = ia;, that would be such an implicit conversion -- ip now points to the first element of ia. It is the exact same as what you wrote, int *ip = &ia[0];
When you write something like *(ia + 2), again, in this context the array is also implicitly converted to a pointer to its first element, kind of like *(&ia[0] + 2). Since we know that ip points to the first element of ia, when you use ia in any context where it gets converted to a pointer, it's the same as using the value of ip. That's why ia[2] and ip[2] work the same.
Related
I'm trying to understand this line of code. Can someone help me? Is it saving the result in the variable val or in the address of the variable val?
*((int*)(&val) +1)= A*(y) + (B - C)
Thank you
&val take the address of val
(int*)(&val) consider this address as a pointer to int
(int*)(&val) +1 increment this address by 1 (times sizeof(int))
*((int*)(&val) +1) = ... assign the right hand side value at this incremented address
It is interpreting val as if it was an array of integers, and storing the result of the right hand expression in its second element. To understand exactly the point of it all you should provide some more context (my guess: is it manipulating the raw content of double values?)
Notice that, depending on the type of val, this may be undefined behavior due to strict aliasing rules.
Divide expression *((int*)(&val) +1) into smaller ones to understand it:
take address of val (&val) and treat it as a pointer to an int (int *)
add 1 +1 to this pointer which means 'move pointer to next int' as it was an array of ints.
finaly by combining * and = apply right hand side expression to int pointed by pointer.
I hope others have answered your question. Adding to what others have said, the same code can be written as follows:
(int*)(&val)[1]= A*(y) + (B - C)
where (int*) will type cast &val as an implicit pointer to an integer which points to the address of val and [1] indicates the first integer location ahead of the location where val is stored.
This is how arrays are interpreted. Say you have an array
int a[10];
For this array, 'a' is a pointer which points to the base address ( address of the element a[0] ), and a[i] is nothing but *(a+i), i.e. the element which is i locations ahead of the first element of the array.
This is not correct code and you should never use it
Imagine this class:
class A {
int number = 10;
public:
void print(){ std::cout << number; }
};
The int number is private for the access not the use!
So how can we access this private int.
Simply:
A obj;
*( (int*) ( &obj ) ) = 100;
obj.print();
output
100
demo
Now if you would have more than one data then how to access?
by this syntax:
*((int*)(&val) +1)
It says:
find the address of the first data,
one index go ahead,
cast it to the int*,
then dereference it,
then initialize it
This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 7 years ago.
I have a few questions. This isn't homework. I just want to understand better.
So if I have
int * b = &k;
Then k must be an integer, and b is a pointer to k's position in memory, correct?
What is the underlying "data type" of b? When I output it, it returns things like 0x22fe4c, which I assume is hexadecimal for memory position 2293324, correct?
Where exactly is memory position '2293324'? The "heap"? How can I output the values at, for example, memory positions 0, 1, 2, etc?
If I output *b, this is the same as outputting k directly, because * somehow means the value pointed to by b. But this seems different than the declaration of b, which was declared int * b = k, so if * means "value of" then doesn't mean this "declare b to the value of k? I know it doesn't but I still want to understand exactly what this means language wise.
If I output &b, this is actually returning the address of the pointer itself, and has nothing to do with k, correct?
I can also do int & a = k; which seems to be the same as doing int a = k;. Is it generally not necessary to use & in this way?
1- Yes.
2- There's no "underlying data type". It's a pointer to int. That's its nature. It's as data type as "int" or "char" for c/c++.
3- You shouldn't even try output values of memory which wasn't allocated by you. That's a segmentation fault. You can try by doing b-- (Which makes "b" point to the "int" before it actual position. At least, to what your program thinks it's an int.)
4- * with pointers is an operator. With any data type, it's another data type. It's like the = symbol. It has one meaning when you put == and another when you put =. The symbol doesn't necesarilly correlates with it meaning.
5- &b is the direction of b. It is related to k while b points to k. For example, if you do (**(&b)) you are making the value pointed by the value pointed by the direction of b. Which is k. If you didn't changed it, of course.
6- int & a = k means set the direction of a to the direction of k. a will be, for all means, k. If you do a=1, k will be 1. They will be both references to the same thing.
Open to corrections, of course. That's how I understand it.
In answer to your questions:
Yes, b is a pointer to k: It contains the address of k in the heap, but not the value of k itself.
The "data type" of b is an int: Essentially, this tells us that the address to which b points is the address of an int, but this has nothing to do with b itself: b is just an address to a variable.
Don't try to manually allocate memory to a specific address: Memory is allocated based of the size of the object once initialized, so memory addresses are spaced to leave room for objects to be allocated next to each other in the memory, thus manually changing this is a bad idea.
* In this case is a de-reference to b. As I've said, b is a memory address, but *b is what's at b's address. In this case, it's k, so manipulating *b is the same as manipulating k.
Correct, &b is the address of the pointer, which is distinct from both k and b itself.
Using int & a = k is creating a reference to k, which may be used as if it were k itself. This case is trivial, however, references are ideal for functions which need to alter the value of a variable which lies outside the scope of the function itself.
For instance:
void addThree(int& a) {
a += 3;
}
int main() {
int a = 3; //'a' has a value of 3
addThree(a); //adds three to 'a'
a += 2; //'a' now has a value of 8
return 0;
}
In the above case, addThree takes a reference to a, meaning that the value of int a in main() is manipulated directly by the function.
This would also work with a pointer:
void addThree(int* a) { //Takes a pointer to an integer
*a += 3; //Adds 3 to the int found at the pointer's address
}
int main() {
int a = 3; //'a' has a value of 3
addThree(&a); //Passes the address of 'a' to the addThree function
a += 2; //'a' now has a value of 8
return 0;
}
But not with a copy-constructed argument:
void addThree(int a) {
a += 3; //A new variable 'a' now a has value of 6.
}
int main() {
int a = 3; //'a' has a value of 3
addThree(a); //'a' still has a value of 3: The function won't change it
a += 2; //a now has a value of 5
return 0;
}
There are compliments of each other. * either declares a pointer or dereferences it. & either declares a (lvalue) reference or takes the address of an object or builtin type. So in many cases they work in tandem. To make a pointer of an object you need its address. To use a pointer as a value you dereference it.
3 - If k is a local variable, it's on the stack. If k is a static variable, it's in the data section of the program. The same applies to any variable, including b. A pointer would point to some location in the heap if new, malloc(), calloc(), ... , is used. A pointer would point to the stack if alloca() (or _alloca()) is used (alloca() is similar to using a local variable length array).
Example involving an array:
int array_of_5_integers[5];
int *ptr_to_int;
int (*ptr_to_array_of_5_integers)[5];
ptr_to_int = array_of_5_integers;
ptr_to_array_of_5_integers = &array_of_5_integers;
So I'm currently reading and learning a code from the internet (related to artificial neural network) and I found a part of the code that I don't understand why it works.
double* inputNeurons;
double* hiddenNeurons;
double* outputNeurons;
This is how it was declared. Then in this next code, it was changed and used as an array?
inputNeurons = new( double[in + 1] );
for ( int i=0; i < in; i++ ) inputNeurons[i] = 0;
inputNeurons[in] = -1; // 'in' is declared in the function as an int
So, I want to understand why and how it works. Did it become an array of "doubles"? If so, in what way can I also use this? Can this be used for struct or even class?
Every array can be treated as a pointer. But that does not mean every pointer is an array. Do not mix this up!
Assuming we have an array int test[..], the variable name also represents the address where the array is stored in the memory. So you could write
int * p = test;
At that moment my pointer p "becomes" an array, where "becomes" means 'points to an array'. Your example is similar - the only difference is that the memory is allocated dynamically (heap) and not on the stack (as in my example).
So how are the elements accessed?
Let's say, we want to get the first element (index 0).
We could say
int i = test[0];
or we could say
int i = *p;
Now we want to get the element at index 1:
int i = test[1];
Or - by using pointer arithmetics we could write
int i = *(p + 1);
In C++ (and C) pointers support indexing operator [] which basically adjusts the value of the pointer by the amount specified times the size of the type pointed.
So basically
inputNeurons[5] = 0;
is equivalent to
*(inputNeurons+5) = 0
Now this doesn't give you any guarantee about the fact that inputNeurons points to an address which is correctly allocated to store at least 6 double values but syntactically it is correct and well defined.
You are just adjusting an address to point to the i-th element of a given type starting from the specified address.
This means that
double x;
double* px = &x;
px[5] = 0;
Is syntactically correct although it is wrong, since px+5 is an address which points to memory which has not been reserved correctly to hold that value.
The pointer of type double (double* inputNeurons;) just gets assigned to point to the beginning of an dynamically allocated array (new( double[in + 1])) of the same type. It does not become an array.
You can do this with any other pointer and regular array of the same type. As a matter of fact an array is a pointer to specific address (to its beginning, i.e. to the element with index: 0).
When you increment the pointer by + 1, that one means 1 * type_size (i.e 1 * size_of_double)
In your case: inputNeurons points to the address of the first element of the array. If you dereference it: *inputNeurons, you will get the value stored at that address (if inputNeurons was an array, it would be equivalent to: inputNeurons[0] ). To access the next element just increment by one (*inputNeurons + 1).
This question already has answers here:
Why p and *p giving the same address when p points to an array?
(3 answers)
Closed 8 years ago.
I found this program in a contest question paper:
#include <iostream>
void main()
{
int a[5] = { 1, 2, 3, 4, 5 };
int *ptr = (int*)(&a + 1);
printf("%d %d ",*(a + 1), *(ptr - 1));
}
The output is 2 5
now when I change the 5th line to int *ptr=(int*)(&a); and printf("%d %d ",*(a + 1), *(ptr));
The output becomes 2 1
In the first case the ptr got the last address of the array+1 and in the second case the ptr got the same address of the array(address of a).
My doubt is why does this assignment show different kind of behavior when the a is incremented and assigned to ptr and when a is assigned to ptr without incrementing?
When you take the address of the array, you get a pointer to an array of 5 ints (that is, int(*)[5]). When you increment that pointer, it moves by the size of an array of 5 ints. So it points to the next array in a sequence of arrays (if you actually had a sequence of arrays). Then when you convert that pointer to int*, it becomes a pointer to the first int of the second (non-existent) array, which is one element after the last element of the first array. So that's what is happening with your first example.
With your second example, you are not incrementing the pointer to the array, so when you convert it to int*, it becomes a pointer to the first int in the array.
&a is a pointer to an integer array of size 5, while ptr is an int*. Thus, &a + 1 increment by the size of an int[5], while pointer arithmetic on an int* changes the value of the pointer by multiples of sizeof(int). Thus, &a + 1 is pointing to the address which is 5*sizeof(int) from the address of a. Casting this to an int* ptr and doing ptr-1 gives you the address of a[4].
&a + 1;
Here, simple a refers to the base address of array i.e address of first element. When you say a+1 compiler will see +1 applied to pointer to an int. So, it would increment by offset which would make it jump to next integer.
However, when you say &a, it means address of that array element ( which is of type int [5]). So, adding one to it means that next offset would be to next array of that type i.e indirectly to one-past end of array. Taking address of one-past-array element is no problem until you don't dereference it.
I'm trying something very simple, well supposed to be simple but it somehow is messing with me...
I am trying to understand the effect of ++ on arrays when treated as pointers and pointers when treated as arrays.
So,
int main()
{
int a[4] = { 1, 4, 7, 9 };
*a = 3;
*(a+1) = 4;
*++a = 4; //compiler error
}
1: So at *(a+1)=4 we set a[1]=4; //Happy
But when *++a = 4;, I'd expect pointer a to be incremented one since ++ is precedent to * and then * kicks in and we make it equal to 4. But this code just does not work... Why is that?
Another problem:
int main()
{
int* p = (int *)malloc(8);
*p = 5;
printf("%d", p[0]);
*++p = 9; //now this works!
printf("%d", p[1]); //garbage
printf("%d", p[0]); //prints 9
}
2: Now *++p = 9; works fine but it's not really behaving like an array. How are two different? This is just incrementing p, and making it equal to 9. If I print p[0], it now prints 9 and I see that though can't access it via p[0] anymore, *(p-1) shows 5 is still there. So indexing a pointer with [0], where exactly does it point to? What has changed?
Thanks a lot all experts!
The array names is not modifiable lvalue so operation ++ is not applied hence ++a that try to modify a is compilation time error (where a is array name).
Note *(a + 1) and *a++ are not same, a + 1 is a valid instruction as it just add 1 but doesn't modify a itself, Whereas ++a (that is equvilent to a = a + 1) try to modify a hence error.
Note 'array names' are not pointer. Pointers are variable but array names are not. Of-course when you assign array name to a pointer then in most expressions array names decays into address of first element. e.g.
int *p = a;
Note p points to first element of array (a[0]).
Read some exceptions where array name not decaying into a pointer to first element?
An expression a[i] is equivalent to *(a + i), where a can be either a pointer or an array name. Hence in your second example p[i] is valid expression.
Additionally, *++p is valid because because p is a pointer (a variable) in second code example.
int a[4] = { 1, 4, 7, 9 };
int *pa=a;
There is one difference between an array name and a pointer that must be kept in mind. A pointer is a variable, sopa=a and pa++ are legal. But an array name is not a
variable; constructions like a=pa and a++ are illegal
int* p = (int *)malloc(8);
Don't cast result of malloc()
Use index with pointer
p[1]=9; // p[1]==*(p+1)