Skip to content

Instantly share code, notes, and snippets.

@sojohnnysaid
Last active January 19, 2021 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sojohnnysaid/094e1ba50da8374f11d3b80699975533 to your computer and use it in GitHub Desktop.
Save sojohnnysaid/094e1ba50da8374f11d3b80699975533 to your computer and use it in GitHub Desktop.
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