Difference between revisions of "C programming/pointers"

From Teknologisk videncenter
Jump to: navigation, search
m
m
 
(One intermediate revision by the same user not shown)
Line 11: Line 11:
  
 
   printf("Value of int <pointer> points to: %d\n", *pointer);
 
   printf("Value of int <pointer> points to: %d\n", *pointer);
 +
 
 +
  // Changing the value of the int <pointer> points to
 +
  *pointer = *pointer + 99;
 +
  printf("<pointer> value %d and <x> value %d\n", *pointer, x);
 +
 +
  // Working the actual addresses
 
   printf("The address contained in <pointer> %p\n", pointer);
 
   printf("The address contained in <pointer> %p\n", pointer);
 
   printf("The address of <x> %p - Should be the same as the above address!\n", &x);
 
   printf("The address of <x> %p - Should be the same as the above address!\n", &x);
Line 16: Line 22:
 
   return(0);
 
   return(0);
 
}
 
}
 +
</source>
  
 
=Review of C Pointer Declarations=
 
=Review of C Pointer Declarations=

Latest revision as of 12:15, 26 May 2015

Basic pointer

The following sourcecode demonstrates the basic pointer:

#include <stdio.h>

int main( void ) {
  int x = 100;
  int *pointer;

  pointer = &x;  // Set pointer to address of <x>

  printf("Value of int <pointer> points to: %d\n", *pointer);
  
  // Changing the value of the int <pointer> points to
  *pointer = *pointer + 99;
  printf("<pointer> value %d and <x> value %d\n", *pointer, x);

  // Working the actual addresses
  printf("The address contained in <pointer> %p\n", pointer);
  printf("The address of <x> %p - Should be the same as the above address!\n", &x);
  printf("The <pointer> has it's own address also, which is %p\n", &pointer);
  return(0);
}

Review of C Pointer Declarations

int *p p is a pointer to int
int *p[13] p is an array[13] of pointer to int
int *(p[13]) p is an array[13] of pointer to int
int **p p is a pointer to a pointer to an int
int (*p)[13] p is a pointer to an array[13] of int
int *f() f is a function returning a pointer to int
int (*f)() f is a pointer to a function returning int
int (*(*f())[13])() f is a function returning ptr to an array[13] of pointers to functions returning int
int (*(*x[3])())[5] x is an array[3] of pointers to functions returning pointers to array[5] of ints