Pointer Syntax Basics by Anand George Pointer variable
Pointer Syntax Basics by Anand George
Pointer variable declaration #include <stdio. h> void main() { int *ptr; int a = 10; ptr = &a; printf ( “%d”, *ptr ); } Here itself some complications.
Different uses of star ( * ) operator 1. 2. 3. Multiplication. ( a * b ) Pointer declaration. ( int *ptr ) Pointer de-referencing. ( *ptr = 10 ) 2 and 3 are completely different and has no relation.
Pointer declaration. ( int *ptr ) • Telling the compiler we want to allocate a variable of size ‘pointer’ which is of type integer pointer ( 32 bit size in a 32 bit app). • ptr is the name of the variable and int* is the data type. • compilers support all below • • int *ptr int* ptr int (*ptr) all confusing, counter intuitive and same meaning.
Pointer de-referencing. ( *ptr = 10 ) • Telling compiler assign value 10 to the memory location pointed by variable ptr. • This operation is called dereferencing of a pointer variable. • This has no similarity or relation with the * you saw in the previous slide.
How do I know which one is which? • the pointer data type declaration * is always at the declaration. • if you see star after that connect to that variable its either multiplication or de-referencing. • int * ptr = 100; • *ptr = 10;
& or address of operator • always gives us the address of a variable. • when it comes to C++ & is going to cause a very similar confusion with respect to reference variables in C++.
Now let’s try to understand what was our code doing #include <stdio. h> void main() { int *ptr; int a = 10; ptr = &a; printf ( “%d”, *ptr ); }
Exercise 1 #include <stdio. h> void main() { int *ptr = 100; *ptr = 10; }
Exercise 2 #include <stdio. h> void main() { int *ptr = 0; printf ( “%d, %d” , ptr, *ptr , &ptr); }
Exercise 3 #include <stdio. h> void main() { int (*ptr) = 100; printf( “%d”, *ptr ); }
Exercise 4 #include <stdio. h> void main() { int *ptr. A = 0; int *ptr. B = 0; int *ptr. C = 0; int a=10, b=20, c=0; ptr. A = &a; ptr. B = &b; ptr. C = &c; *ptr. C = *ptr. B**ptr. A; printf("%d", *ptr. C ); }
Summary • Pointer syntax basics • Three different uses of * operator • & operator.
Thank you
- Slides: 14