Last active
January 19, 2021 22:54
-
-
Save sojohnnysaid/094e1ba50da8374f11d3b80699975533 to your computer and use it in GitHub Desktop.
Learning how to use typedef and struct
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
#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