c ++, pointer example

Example 1: poiner in c

int c, *pc;

// pc is address but c is not
pc = c; // Error

// &c is address but *pc is not
*pc = &c; // Error

// both &c and pc are addresses
pc = &c;

// both c and *pc values 
*pc = c;

Example 2: c function pointer

//Declaration of a pointer to a function that takes an integer 
//and returns an integer.
int (*f_ptr)(int);

//Assignment of a function foo to the function pointer f_ptr declared above.
f_ptr = foo;

//Calling foo indirectly via f_ptr, passing the return value of foo to r.
int r = f_ptr(v);

//Assigning an address of a function to the function pointer f_ptr,
//then calling foo by dereferencing the function pointer.  
f_ptr = &foo;
int r = (*f_ptr)(v);

Example 3: poiner in c

#include <stdio.h>
int main()
{
    int var =10;
    int *p;
    p= &var;

    printf ( "Address of var is: %p", &var);
    printf ( "\nAddress of var is: %p", p);

    printf ( "\nValue of var is: %d", var);
    printf ( "\nValue of var is: %d", *p);
    printf ( "\nValue of var is: %d", *( &var));

    /* Note I have used %p for p's value as it represents an address*/
    printf( "\nValue of pointer p is: %p", p);
    printf ( "\nAddress of pointer p is: %p", &p);

    return 0;
}

Example 4: How to use pointers in C

myvar = 25;
foo = &myvar;
bar = myvar;

Tags:

Misc Example