Structures1 - Structures in C An array allows you to store...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Structures in C An array allows you to store related variables of the same type in the same essential structure. But what if you wanted to store related information in the same structure that was NOT of the same type. For example, consider the situation where you want to store information about a block that has a number on it, a letter on it, and is painted a particular color. C allows you to declare a struct. Once you do so, you can create variables of this type. Here is the general syntax: struct <struct_name> { <type1> <var1>; <type2> <var2>; .... <typen> <varn>; }; Here is how you would declare a struct for a block: struct block { int number; char letter; char color[15]; }; Typically, you would include this definition at the top of your file, after your #defines. Once you declare a type, you may declare variables of that type. Let's looks at a small example using the block type:
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
In order to access a component of a record, you have to use the . operator. Thus, if the name of your block is first, as it is below, you can access the number component of THAT specific block by the expression first.number. Let's look at an example utilizing this syntax: #include <stdio.h> struct block { int number; char letter; char color[15]; }; int main() { struct block first; printf("Enter the number on the first block.\n"); scanf("%d", &first.number); printf("Enter the letter on the first block.\n"); scanf("%c", &first.letter); printf("Enter the color of the first block.\n"); scanf("%s", &first.color); printf("Block info: %d %c %s\n", first.number, first.letter, first.color); } Although we only have simple components for this particular
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 8

Structures1 - Structures in C An array allows you to store...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online