Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Learning how to use typedef and struct
#include <stdio.h>
// create a typedef
// create a variable using your "new" data type
// using typedef we can create an alias to a
// common data type to give context
typedef char TEXT;
// by using typedef
// we can skip the struct keyword
// when declaring variables of our
// struct's name which is SUPERHERO
// notice on line 28 we don't declare it
// struct SUPERHERO a we just declare
// SUPERHERO a
typedef struct
{
// notice the star indicating
// this data type is a pointer
// which is what we need for strings (char * or char mytext[])
TEXT * name;
TEXT * ability;
}SUPERHERO;
int main(void)
{
SUPERHERO a;
a.name = "superman";
a.ability = "I can fly";
printf("I am %s and %s\n", a.name, a.ability);
SUPERHERO b;
b.name = "batman";
b.ability = "I'm rich";
printf("I am %s and %s\n", b.name, b.ability);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment