|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/jun29/pointers.c
/*
This just demonstrates accessing values through pointers
Note: When declaring pointers: you should initialize your pointer variables to NULL
if you don't have a variable to assign it to.
Ex: int *ptr = NULL;
*/
#include <stdio.h>
int main(){
int x = 5; //declaring an integer x, setting it equal to 5
int *p = &x; //declaring a pointer, pointing it to the variable x using the assignment operator
//should print 5 both times
printf("Variable: %d\n", x);
printf("Through pointer: %d\n", *p);
//printf("Address stored in variable: %x\n", &p); //this prints the address
x = 6; //change variable x to 6
//both should print 6
printf("Variable: %d\n", x);
printf("Through pointer: %d\n", *p);
x++;//increment x
//both should print 7
printf("Variable: %d\n", x);
printf("Through pointer: %d\n", *p);
(*p)++; //increment x through the pointer
//due to rules regarding operator precidence, we have
//to have parentheses around the *p in order to increment a
//number through the pointer
//both should print 8
printf("Variable: %d\n", x);
printf("Through pointer: %d\n", *p);
return 0;
}
|