Learn How to Program in C

by
Dr. Kristin Switala

Introduction

Directives

Variables

Conditionals

Loops

Arrays

Pointers

Strings

Functions

Structures


Site Map

Pointers (b)

In This Section:
Information Storage, Variable Addresses, Addresses and Viewer Input, Addresses and Loops


Information Storage

We know that computers store information in memory. Each byte of information has a specific location in the memory area. This location is called the address.

Whenever you use a variable, the value of the variable is stored in a specific address. This is why we used the ampersand & with the scanf function, like this:

scanf("%d", &year);

The & is called the address of operator. It tells the computer where this variable's value is stored in memory.


Variable Addresses

In the computer's memory area, each byte address is labelled with a hexadecimal number. To discover the address of a variable, use the %p format specifier, like this:

printf("\nThe variable 'year' is stored in byte %p.", &year);

Notice that we use the address of operator & in front of the variable, when we want to get the address, rather than the value of the variable.

Let's write a program that identifies the addresses of variables.

#include<stdio.h>
void main( )
{
int year = 1834;
float price = 19.95f;
printf("\nThe address of 'year' is %p.", &year);
printf("\nThe address of 'price' is %p.", &price);
}

Type this source code in your editor and save it as address.c then compile it, link it, and run it.


Addresses and Viewer Input

We can also discover the where the computer stores viewer input. For example, this script stores the viewer's age in a particular byte in memory:

#include<stdio.h>
void main( )
{
int age;
printf("\nHow old are you? ");
scanf(" %d", &age);
printf("\nYou are %d years old and this variable's address is %p", age, &age);
}

Type this source code in your editor and save it as ageaddre.c then compile it, link it, and run it.


Addresses and Loops

You can use a loop to discover the addresses of a specific set of numbers. This program gets the addresses for the numbers 27990 - 28000:

#include<stdio.h>
void main( )
{
int number;
printf("\nNumber\tAddress");
for(number = 27990; number < 28000; ++number)

printf("\n%d\t%p", number, &number);

}

Type this source code in your editor and save it as loopaddr.c then compile it, link it, and run it.

Copyright
© 2001
Kristin Switala
Hosted by www.Geocities.ws

1