Skip to content

Instantly share code, notes, and snippets.

@bradmontgomery
Last active October 8, 2019 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradmontgomery/2e68f22d8f81313414a4e665b9221594 to your computer and use it in GitHub Desktop.
Save bradmontgomery/2e68f22d8f81313414a4e665b9221594 to your computer and use it in GitHub Desktop.
A simple example of the * and & operators.
/* Pointers!
*
* Address of and value at...
*
* See this great stack overflow answer for an additional
* discussion on the topic.
*
* https://stackoverflow.com/a/2094715/182778
*
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 42; // A plain old integer.
int *p = &i; // A pointer to i's address.
// Let's see some info about the integer's memory address & value.
printf("--- i is an integer ---\n");
printf("The value stored at: i = %d\n", i);
printf("It's memory address is: &i = %p\n", &i);
// Now, what about p?
printf("\n--- p is a pointer to an integer (i) ---\n");
printf("At memory address: p = %p\n", p);
printf("The value that p points to is: %d\n", *p);
// You can change the value of p!
*p = 5;
printf("After running *p = 5\n");
printf("*p = %d\n", *p);
printf(" p = %p\n", p);
printf("&i = %p\n", &i);
printf(" ^^^^^^^^^^^^^^ are these the same?\n\n");
printf("But what is i?\n");
printf(" i = %d\n", i);
printf("* Gives you the value at a pointer\n");
printf("& Gives you the address of a variable.\n\n");
return 0;
}
/*
* This example illustrates structs & pointers to structs!
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct Person {
char *name;
int age;
} Person;
int main()
{
Person p;
p.name = "brad";
p.age = 12;
printf("Name (p.name): %s\n", p.name);
printf("Age (p.age) : %i\n", p.age);
Person *x = &p;
printf("But x is a pointer to the Person as well!\n");
printf("x->name: %s\n", x->name);
printf("x->age: %i\n", x->age);
// But we can chnage the person thru the pointer, too!
x->age = 100;
printf("Name (p.name): %s\n", p.name);
printf("Age (p.age): %i\n", p.age);
printf("x's address is: %p\n", x);
printf("p's address is: %p\n", &p);
// Just illustrating that we have one other variable
// containing a Person type.
Person o;
o.name = "Ophelia";
o.age = 35;
printf("Name (o.name): %s\n", o.name);
printf("Age (o.age): %i\n", o.age);
printf("o's address is: %p\n", &o);
return 0;
}
@bradmontgomery
Copy link
Author

Copy this code into pointers.c, compile it, then run ./pointers to see it in action.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment