user:psechris:portfolio:cprogproject6
Table of Contents
Project: Pointer Fun!
A project for CSCS 1320 by Paul Sechrist during the Spring 2013.
Objectives
This project is to help learn about pointers, what they are used for, and how to use them.
Code
Pointer Fun 1
#include <stdio.h> #include <stdlib.h> int main() { char a, *b; a = 'a'; // what numeric value is being stored in the variable a? Why? b = &a; printf("a contains '%c'\n", a); printf("a's address is 0x%X\n", &a); printf("-----------------------\n"); printf("b dereferenced contains '%c'\n", *b); printf("b contains 0x%X\n", b); printf("b's address is 0x%X\n", &b); return(0); }
Pointer Fun 2
#include <stdio.h> #include <stdlib.h> int main() { char *a; a = (char *) malloc (sizeof(char)); *a = 48; //fprintf(stdout, "*a is %c\n", *a); return(0); }
Pointer Arrays
- 1
#include <stdio.h> #include <stdlib.h> #define NUM_SCORES 5 #define SCORE0 87 #define SCORE1 92 #define SCORE2 97 #define SCORE3 83 #define SCORE4 79 int main() { unsigned char *scores; float average; scores = (unsigned char *) malloc (sizeof(unsigned char) * NUM_SCORES); *(scores+0) = SCORE0; *(scores+1) = SCORE1; *(scores+2) = SCORE2; *(scores+3) = SCORE3; *(scores+4) = SCORE4; /* Please provide the equation to do average of the scores */ //average = EQUATION TO DO AVERAGE /* Display the scores via array referencing and then the average. * %f can be used to display a floating point value. */ //fprintf(stdout, "YOUR FORMATTED TEXT STRING", LIST OF VARIABLES); return(0); }
Execution
Reflection
Pointer Fun 1
- What do the variables a and b have in common?
- Where do they differ?
- If you change variable a, what will happen to b?
- If you change variable b, will it impact a?
- How can you change b without breaking things?
Pointer Fun 2
- If we uncomment that fprintf() line, what will be displayed?
- What is malloc() doing?
- Why is it needed?
References
user/psechris/portfolio/cprogproject6.txt · Last modified: 2013/03/11 10:38 by psechris