|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/jul12/struct.c
/*
defining a simple struct
structs are similar to arrays, but a struct may contain data of different
data types. Each element of data in the struct is named in the same way
individual variables are.
So a struct can be thought of as a collection of variables under one name
*/
#include <stdio.h>
//we define structs outside and above of main
//typedef is a keyword that allows us to rename datatypes
//the typedef keyword here will allow us to give our
//struct a single variable name, so we can declare it
//just like a regular variable in main
typedef struct stuff {
int a, b;
}thing;
//above, we have a struct named stuff, that has just two integers
//with the typedef keyword, we named the datatype for our struct "thing"
int main(){
int x = 3;
thing y; //declaring a variable that uses our new struct as a datatype
// without the typedef statement, we'd need to type in "struct stuff y"
// to do what we just did above
y.a = 4; //to access a member of our struct to set a variable to something
// we use the format variable.member to do this
//in that case, we're setting variable y dot member a to 4,
y.b = 10;
printf("Struct stuff a = %d, b = %d\n", y.a, y.b);
return 0;
}
|