4.2 Structure Syntax


Defining a structure

Constructing a structure requires the usage of the struct keyword. Once you do that you can fill in as many variables as needed. Keep in mind you must put the structure itself outside of the main function.
#include <stdio.h> #include <string.h> struct Computer { // String variables char model[50]; char manufacturer[50]; char color[100]; // Integer variables int yearReleased; int numberOfKeys; }; int main() { //code goes here }

Accessing a structure

Once a structure has been defined. It can now be used similar to any other variable or array. Accessing it requires to declare an entire structure to be declared.
#include <stdio.h> #include <string.h> struct Computer { //code goes here }; int main() { //Declaring the computer structure struct macBookPro Computer; struct alienWareR13 Computer; //Using strcpy since there are no strings in C in the default library strcpy(macBookPro.model, "MacBook"); strcpy(macBookPro.manufacturer, "Apple"); strcpy(macBookPro.color, "White"); //Assigning values to each variable within the type computer macBookPro.yearReleased = 2021; macBookPro.numberOfKeys = 109; //Doing the same for the AlienWareR13 strcpy(alienWareR13.model, "C Programming"); strcpy(alienWareR13.manufacturer, "Nuha Ali"); strcpy(alienWareR13.color, "C Programming Tutorial"); alienWareR13.yearReleased = 2021; alienWareR13.numberOfKeys = 0; //Technically not including an external keyboard }

Previous Section

Next Section

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.