+ 5
Changing values using pointers
why does sometimes we write *ptr = a+6 when int*ptr = &a and sometimes ptr = a+6 are they both correct?
8 Answers
+ 17
Lets declare integer variable and a pointer to it:
int a;
int *ptr = &a;
ptr is a memory address of 'a' variable and *ptr is value which is stored in that nemory address.
If you want to change value of variable using pointer, then you should use * :
*ptr = 6; // a = 6
*ptr = *ptr + 3; // a becomes 9
When you need to change value, then, yes, use *.
When you need to walk through the memory, then don't use *.
+ 4
A drawing can show the case a little bit better (according to an advice by Nick Parlante):
https://code.sololearn.com/WCafCnD3hSsn/?ref=app
+ 3
@microBIG
E.g. 'a' is an array of integers.
int *ptr = a; // means that now ptr points to the beginning of the array (its first element)
*ptr = a + 6; // after that ptr points to the 7th element of array 'a' (*ptr equals a[6]).
You can use ptr++ in loop for sequential run through the elements of your array.
Be careful using pointers
In this *ptr = a + 6; would show error.
ptr = a + 6; //points to the 7th element of array 'a'
+ 2
E.g. 'a' is an array of integers.
int *ptr = a; // means that now ptr points to the beginning of the array (its first element)
*ptr = a + 6; // after that ptr points to the 7th element of array 'a' (*ptr equals a[6]).
You can use ptr++ in loop for sequential run through the elements of your array.
Be careful using pointers
+ 2
suppose a is an int and your adding 6 to its value,
also what i meant was
weather we should * or not
+ 2
microBIG
+ 2
could you give an example of when not to use *
+ 2
I've already given you example with arrays. Elements of array are situated one by one in memory, so when you increase/decrease ptr by 1 you go to the next/previous array element.
In case of pointers to integers (not in arrays) it won't have sense until you won't align your memory (using memalign(), for example)