6.20 Code Layout6 Notes6.18 6.19 Pointers - 1

6.19 Pointers - 1

An example program that:

  1. uses pointers to return values from a function,

/* Program to look at pointers                 */ 
/* L Taber   Feb 17, 2001   PCC                */

#include <stdio.h> 
#include <stdlib.h>

                      /* returns three results */
int sumANDswap(int *a, int *b);
int printab(int x, int y, char *string);

int a = 1;            /* external variable     */
                      /* initilized only once  */
int *ptr;

int main() 
{
int b;                /* auto variable         */
int sum;              /* for return value      */

ptr = malloc( sizeof a );
*ptr = 42;
b=5+a;

printab(a, b,    "a & b    ");
sum = sumANDswap(&a, &b);
printab(a, b,    "a & b    ");
printf("sum= %d\n\n", sum);

printab(b, *ptr, "b & *ptr ");
sum = sumANDswap(&b, ptr);
printab(b, *ptr, "b & *ptr ");
printf("sum= %d\n", sum);
}

                        /* returns three results */
int sumANDswap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
return( *a + *b );
}

   /* strings are really character pointers ! */
int printab(int x, int y, char *string)
{
return printf(" %s %d   %d\n", string, x, y);
}

This program is available by anonymous ftp at:
ftp://lt.tucson.az.us/pub/c/prt1.c.

The anotated output on my system looked like this:

 a & b     1   6
 a & b     6   1
sum= 7

 b & *ptr  1   42
 b & *ptr  42   1
sum= 43

I am using gcc version 2.95.2 20000220 (Debian GNU/Linux).

  1. Note the memory layout. Executable code, global/static variables, the heap, and then the stack.
  2. The heap is just after the global/static variables.
  3. The addresse of main() does not change.
  4. The addresse of a does not change.
  5. A second copy of b is placed on the stack at a lower address.
  6. A second set of storage is set aside for the second int on the malloc-ed. The heap is grows toward the stack.

Instructor: Louis Taber, louis.taber.at.pima at gmail dot com (520) 206-6850
My web site in Cleveland, OH
The Pima Community College web site

6.20 Code Layout6 Notes6.18 6.19 Pointers - 1