Created
December 23, 2014 03:25
-
-
Save douganger/7cb565364fa0897b2cf1 to your computer and use it in GitHub Desktop.
A quick example using pointers and printf in C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright (c) 2014 Doug Anger. This work is licensed under the Creative Commons | |
Attribution 4.0 International License. To view a copy of this license, visit | |
http://creativecommons.org/licenses/by/4.0/. | |
*/ | |
#include <stdio.h> | |
int main(){ | |
int x; | |
// Declaring an int reserves the needed amount of RAM to hold that int. That | |
// memory has a unique address, which we can access with the & operator. The | |
// opposite of & is *, which designates a pointer, so we can go ahead and | |
// create a pointer to x even before we assign it a value. | |
int* y = &x; | |
// This is a pointer to x's location in memory. The * makes it a pointer. | |
// Now let's go ahead and assign a value to x, so we can see how it works. | |
x = 15; | |
// Now we'll see how the % symbol works in printf. The % symbol is followed | |
// by a letter or letters that specify what kind of variable to expect. | |
// printf uses %i to format an int, passed in the next argument: | |
printf("int x = %i. (We can print more stuff here.)\n", x); | |
// This will print everything in quotes until it gets to the % character. At | |
// that point it will format the variable passed in the next argument. Then | |
// it will continue printing what we typed in quotes, including the newline, | |
// represented by \n. | |
// Showing how printf uses %lu to format a long unsigned int: | |
printf("int* y = %lu (the memory address of x.)\n", (unsigned long int) y); | |
// We coerced y into a long unsigned int because a regular int can't hold a | |
// large enough value to address every location in RAM. | |
// Showing how pointers work by printing x using the pointer *y: | |
printf("int x = %i\n", *y); | |
// The * and & operators are opposites. Just as &x gives us the memory | |
// location of x, *y gives us the data stored at the memory location y. This | |
// becomes a very useful way to pass variables into functions in a way that | |
// allows the function to modify that original variable. | |
// Now we return 0 to tell the OS that we are exiting normally. A non-zero | |
// value would mean that we exited because of an error. | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment