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

21st Oct 2018, 5:49 AM
Arun Sharma
Arun Sharma - avatar
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 *.
21st Oct 2018, 8:44 AM
microBIG
microBIG - avatar
+ 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
28th Oct 2018, 11:01 AM
Rolf Straub
Rolf Straub - avatar
+ 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'
12th Jul 2019, 6:17 AM
Parth Salat
Parth Salat - avatar
+ 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
21st Oct 2018, 7:32 AM
microBIG
microBIG - avatar
+ 2
suppose a is an int and your adding 6 to its value, also what i meant was weather we should * or not
21st Oct 2018, 8:04 AM
Arun Sharma
Arun Sharma - avatar
+ 2
microBIG
21st Oct 2018, 8:05 AM
Arun Sharma
Arun Sharma - avatar
+ 2
could you give an example of when not to use *
21st Oct 2018, 8:51 AM
Arun Sharma
Arun Sharma - avatar
+ 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)
21st Oct 2018, 9:43 AM
microBIG
microBIG - avatar