Pointer Activity
- Create variables for a character, a string, an integer, and a floating-point number.
- Create pointers for each of those variables. Ideally, use the same name as the variable but add a p in front of the name (For example: (total and total)
- Ask the user to enter information for each of these variables one at a time. For each variable tell them what they should enter. (For example: “Enter a single character” or “Enter a floating-point number”) Read in the information and put it in the variables.
- Make each pointer point to the respective variable.
- Print out values for the four variables without using the variables themselves. Only use the pointers.
- In addition print out the addresses of the memory locations that each pointer points to.
- The output should look like the bottom sample.
Character: h
Integer: 8
String: Manny
Floating Point: 4.5
Character Pointer: XXXXXXXX
Integer Pointer: XXXXXXXX
String Pointer: XXXXXXXX
Solution:
#include < stdio.h>
#include < string.h>
/*
* Pointer Activity
*/
int main(int argc, char** argv) {
// 1. Create variables for a character, a string, an integer, and a floating point number.
char a;
char b[255];
int c;
float d;
// 2. Create pointers for each of those variables. Ideally, use the same name as the variable but add a
// p in front of the name (For example: (total and ptotal)
char *pa;
char *pb;
int *pc;
float *pd;
// 3. Ask the user to enter information for each of these variables one at a time. For each variable tell
// them what they should enter. (For example: “Enter a single character” or “Enter a floating point
// number”) Read in the information and put it in the variables.
printf( "Enter a single character: " );
scanf( "%c", &a );
printf( "Enter a string: " );
scanf( "%s", b );
printf( "Enter an integer: " );
scanf( "%d", &c );
printf( "Enter a floating point number: " );
scanf( "%f", &d );
// 4. Make each pointer point to the respective variable.
pa = &a;
pb = b;
pc = &c;
pd = &d;
// 5. Print out vales for the four variables without using the variables themselves. Only use the pointers.
printf( "\tCharacter: %c\n", *pa );
printf( "\tInteger: %d\n", *pc );
printf( "\tString: %s\n", pb );
printf( "\tFloating Point: %f\n", *pd );
// 6. In addition print out the addresses of the memory locations that each pointer points to.
printf( "\tCharacter Pointer: %p\n", pa );
printf( "\tInteger Pointer: %p\n", pc );
printf( "\tString Pointer: %p\n", pb );
printf( "\tFloating Point Pointer: %p\n", pd );
// 7. Output should look like the bottom sample.
// Character: h
// Integer: 8
// String: Manny
// Floating Point: 4.5
// Character Pointer: XXXXXXXX
// Integer Pointer: XXXXXXXX
// String Pointer: XXXXXXXX
return 0;
}