0
Guys plz explain me what is int* a and int a* and i have seen these types in lot of codes i dont understand this and plz show an easy example of this to understand more clearly
5 Réponses
+ 1
check the "pointers" topic. it is not obvious theme, but it is quite useful feature
0
imagine you want to store something. you need a box. that box needs to have the minimum size of the thing you want to store. a pointer ( int* a or int *a ) is the box. when you call a pointer ( a ) you call the location of the box, not the contents ( *a ) itself. you just need to imagine that those boxes position can be changed without changing the box contents. and you can have a box 6 times larger than the object to store 6 of them.
0
another analogy:
imagine we have a pointer ( webpage ).
imagine i want you to see my webpage. instead of me telling you to write all the code needed for that page, which is the content of the page( *webpage ), i could tell you the url ( webpage ). the url points to the webpage contents. which is faster and easier, the url or writing all the code?
0
thanks garme kain i understand now and could u plz write an example on this ?
0
You create an int pointer.
int *myptr;
You have to create the box's size:
myptr = new int;
or, if you want to create space for more than one int element:
myptr = new int[2];
now myptr has space for two ints, and behaves like an array.
Lets populate myptr:
for (int i = 0; i < 2; i++) {
myptr[i] = i + 1;
}
this is equivalent to
for (int i = 0; i < 2; i++) {
*(myptr + i) = i + 1;
}
Now myptr is a 2 element array and has the values {1,2}
doing *myptr or myptr[0] returns 1, and *(myptr + 1) or myptr[1] returns 2.
Ask for anything you want to understand.