Created
September 18, 2012 13:42
-
-
Save nhunzaker/3743177 to your computer and use it in GitHub Desktop.
Explorations in C
This file contains hidden or 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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
// A simple struct, we'll use "PersonStruct" | |
// for clarity | |
struct PersonStruct | |
{ | |
char *name; | |
int age; | |
int height; | |
int weight; | |
}; | |
// By defining a "Person" type, | |
// we can pass the value back and forth | |
// without using a pointer (and thus we | |
// doint have to worry about the stack | |
// clearing the value) | |
// | |
// UPDATE: We can DRY this out by passing the struct | |
// instead of redefining properties | |
typedef struct PersonStruct Person; | |
// We can use this function to create a person | |
// and return it. | |
Person createPersonStack() | |
{ | |
Person guy; // Notice we don't need to use a pointer | |
guy.name = "Nate"; | |
guy.age = 23; | |
guy.height = 72; | |
guy.weight = 155; | |
return guy; | |
} | |
struct PersonStruct *createPersonHeap() | |
{ | |
// Create a Person using our struct with a pointer | |
// Note that we use malloc so that the pointer | |
// isn't cleared from the stack when this function | |
// ends (causing a segfault when accessing a property of | |
// the returned Person, "guy" | |
struct PersonStruct *guy = malloc(sizeof(struct PersonStruct)); | |
assert(guy != NULL); // Let's make sure we have enough memory! | |
// Message notation... | |
guy->name = "Nate"; | |
guy->age = 23; | |
// Dot donation... | |
(*guy).height = 72; | |
(*guy).weight = 155; | |
return guy; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
Person me = createPersonStack(); | |
printf("Stack Person: %s\n", me.name); | |
struct PersonStruct *otherMe = createPersonHeap(); | |
printf(" Heap Person: %s\n", otherMe->name); | |
free(otherMe); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment