How to Work with Pointers in C Programming

The pointer’s power in C programming comes from both its split personality as well as from its ability to change values, such as a variable.

In More Pointer Fun, three char variables are declared at Line 5 and initialized all on Line 8. (They are stacked up on a single line so that the Listing wouldn’t get too long.) A char pointer is created at Line 6.

MORE POINTER FUN

#include <stdio.h>
int main()
{
 char a,b,c;
 char *p;
 a = 'A'; b = 'B'; c = 'C';
 printf("Know your ");
 p = &a;  // Initialize
 putchar(*p); // Use
 p = &b;  // Initialize
 putchar(*p); // Use
 p = &c;  // Initialize
 putchar(*p); // Use
 printf("s\n");
 return(0);
}

Lines 11 and 12 set up the basic operation in the code: First, pointer p is initialized to the address of a char variable. Second, the * (asterisk) is used to peek at the value stored at that address. The *p variable represents that value as a char inside the putchar() function. That operation is then repeated for char variables b and c.

Exercise 1: Create a new project by using the source code from More Pointer Fun. Build and run.

Here is the behavior of pointer variable p as the code runs:

image0.jpg

Exercise 2: Write a program that declares both an int variable and an int pointer variable. Use the pointer variable to display the value stored by the int variable.

The *pointer operator works both ways. Just as you can grab a variable’s value, as shown in More Pointer Fun, you can also set a variable’s value. Refer to Assigning Values by Using a Pointer.

ASSIGNING VALUES BY USING A POINTER

#include <stdio.h>
int main()
{
 char a,b,c;
 char *p;
 p = &a;
 *p = 'A';
 p = &b;
 *p = 'B';
 p = &c;
 *p = 'C';
 printf("Know your %c%c%cs\n",a,b,c);
 return(0);
}

Line 5 in Assigning Values by Using a Pointer declares three char variables. These variables are never directly assigned values anywhere in the code. The p variable, however, is initialized thrice (Lines 8, 10, and 12) to the memory locations of variables a, b, and c. Then the *p variable assigns values to those variables (Lines 9, 11, and 13.) The result is displayed by printf() at Line 14.

Exercise 3: Copy the source code from Assigning Values by Using a Pointer into your editor. Build and run the program.

Exercise 4: Write code that declares an int variable and a float variable. Use corresponding pointer variables to assign values to those variables. Display the results by using the int and float variables (not the pointer variables).

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.