Computer Science

Structures in C

Structures in C are user-defined data types that allow the grouping of variables of different data types under a single name. They are used to represent a record, which is a collection of related data items. Structures can be used to create complex data structures such as linked lists, trees, and graphs.

Written by Perlego with AI-assistance

12 Key excerpts on "Structures in C"

  • Book cover image for: Learn C Programming from Scratch
    eBook - ePub

    Learn C Programming from Scratch

    A step-by-step methodology with problem solving approach (English Edition)

    typedef keyword assigns an alternate label for an existent data type. This can be useful for making code more readable or creating a new data type with a more meaningful name.
    For example, the following code creates a new data type called myint that is equivalent to int :
    typedef int myint;
    The struct keyword is used to create a new user-defined data type called a structure that can contain multiple variables of different data types. Each variable in a struct is called a member and is accessed using the dot notation.
    For example, the following code defines a struct called person that contains three members, name , age, and address :
    struct person { char name [20]; int age; char address [50]; };
    We can also create a new type of name for struct using typedef .
    For example: typedef struct person Person;
    In this way, we can create an instance of the struct person using the new type name Person :
    Person p1;
    User-defined data types can be used in a variety of ways in C programming, such as passing them as function arguments or using them as members of other structures or unions, and it is important to use them correctly to make the most of their capabilities.
    Let us examine Structure and Union data types in detail. Structures
    Arrays allow the defining of different types of variables that can hold several data items of the same data types (homogenous). Similarly, structure is another user-defined data type we can use in C to combine data of different kinds.
    Structures are used to represent a record. Say if we want to keep track of employees in a company. We might want to keep up with the following attributes about each employee: Emp_ID Name Parentage Address Phone_No Salary
    It is convenient to organize related data by defining a new data type with various members by declaring a structure in C. In a program, things or items like a person, a student, or an employee are frequently represented by structures. They give you a means to collect related data and work with it as a single entity.
  • Book cover image for: Data Structures with C Programming
    • Anil Kumar Yadav, Vinod Kumar Yadav(Authors)
    • 2019(Publication Date)
    • Arcler Press
      (Publisher)
    DATA STRUCTURES 1 CHAPTER CONTENTS 1.1. Introduction ........................................................................................ 2 1.2. Data Structure Basic Terminology ....................................................... 2 1.3. Data Structure ..................................................................................... 3 1.4. Introduction To Algorithm ................................................................... 8 1.5. Basic Concept of Function ................................................................ 13 1.6. Basic Concept of Pointers ................................................................. 19 1.7. Introduction To Structure ................................................................... 22 1.8. Dynamic Memory Allocation In Data Structure ................................. 28 Data Structures with C Programming 2 1.1. INTRODUCTION In the Computer Programming or Software development, Data Structures is one of the most valuable roles for computer engineers. Use of appropriate data structures enables a computer system to perform its task more efficiently, by influencing the ability of computers to store and retrieve data from any location in its memory. A data structure is a method of how storing data on a computer so that it can be used efficiently. In Computer Programming we are using different types of data to perform, store, access and sent data and information. Computers cannot do without data, so organizing that data is very important. If that data is not organized effectively, it is very difficult to perform any task on that data. If it is organized effectively then any operation can be performed easily on that data. 1.2. DATA STRUCTURE BASIC TERMINOLOGY 1.2.1. Data and Data Types Data are a group of specific facts, numbers, character, and figures. A data item refers to a single unit of values. Data is an unprocessed form of information.
  • Book cover image for: Low-Level Programming
    eBook - PDF

    Low-Level Programming

    C, Assembly, and Program Execution on Intel® 64 Architecture

    • Igor Zhirkov(Author)
    • 2017(Publication Date)
    • Apress
      (Publisher)
    A structure is a data type which packs several fields. Each field is a variable of its own type. Mathematics would probably be happy calling structures “tuples with named fields.” To create a variable of a structural type we can refer to the example shown in Listing 9-38 . There we define a variable d which has two fields: a and b of types int and char , respectively. Then d.a and d.b become valid expressions that you can use just as you are using variable names. Listing 9-38. struct_anon.c struct { int a; char b; } d; d.a = 0; d.b = 'k'; This way, however, you only create a one-time structure. In fact, you are describing a type of d but you are not creating a new named structural type. The latter can be done using a syntax shown in Listing 9-39 . CHAPTER 9 ■ TYPE SYSTEM 168 Listing 9-39. struct_named.c struct pair { int a; int b; }; ... struct pair d; d.a = 0; d.b = 1; Be very aware that the type name is not pair but struct pair , and you can not omit the struct keyword without confusing the compiler. The C language has a concept of namespaces quite different from the namespaces in other languages (including C++). There is a global type namespace, and then there is a tag-namespace, shared between struct , union , and enum datatypes. The name following the struct keyword is a tag. You can define a structural type whose name is the same as other type, and the compiler will distinguish them based on the struct keyword presence. An example shown in Listing 9-40 demonstrates two variables of types struct type and type , which are perfectly accepted by the compiler. Listing 9-40. struct_namespace.c typedef unsigned int type; struct type { char c; }; int main( int argc, char** argv ) { struct type st; type t; return 0; } It does not mean, though, that you really should make types with similar names. However, as struct type is a perfectly fine type name, it can be aliased as type using the typedef keyword, as shown in Listing 9-41 .
  • Book cover image for: ANSI C Programming
    eBook - ePub

    ANSI C Programming

    Learn ANSI C step by step

    The program becomes more difficult to handle as the number of items relating to the book goes on increasing. For example, we would be required to use a number of arrays, if we also decide to store name of the publisher, date of purchase of book, etc. To solve this problem, C provides a special data type—the structure.
    A structure contains a number of data types grouped together. These data types may or may not be of the same type. The following example illustrates the use of this data type.
    #include <stdio.h> int main() {   struct book   {    char name;    float price;    int pages;   };   struct book b1, b2, b3;   printf ("Enter names, prices & no. of pages of 3 books\n");   scanf ("%c %f %d", &b1.name, &b1.price, &b1.pages);   scanf ("%c %f %d", &b2.name, &b2.price, &b2.pages);   scanf ("%c %f %d", &b3.name, &b3.price, &b3.pages);   printf ("And this is what you entered\n");   printf ("%c %f %d\n", b1.name, b1.price, b1.pages);   printf ("%c %f %d\n", b2.name, b2.price, b2.pages);   printf ("%c %f %d\n", b3.name, b3.price, b3.pages);   return 0; }
    And here is the output… Enter names, prices and no. of pages of 3 books A 100.00 354 C 256.50 682 F 233.70 512 And this is what you entered A 100.000000 354 C 256.500000 682 F 233.700000 512 This program demonstrates two fundamental aspects of structures: (a) declaration of a structure (b) accessing of structure elements Let us now look at these concepts one by one.

    Declaring a Structure

    In our example program, the following statement declares the structure type: struct book {   char name;   float price;   int pages; };
    This statement defines a new data type called struct book . Each variable of this data type will consist of a character variable called name , a float variable called price and an integer variable called pages . The general form of a structure declaration statement is given below:
    struct <structure name> {   structure element 1;   structure element 2;   structure element 3;   ……   …… };
    Once the new structure data type has been defined, one or more variables can be declared to be of that type. For example, the variables b1 , b2 , b3 can be declared to be of the type struct book , as,
    struct book b1, b2, b3;
    This statement sets aside space in memory. It makes available space to hold all the elements in the structure—in this case, 7 bytes—one for name , four for price and two for pages
  • Book cover image for: Foundations of Data Intensive Applications
    eBook - PDF

    Foundations of Data Intensive Applications

    Large Scale Data Analytics under the Hood

    • Supun Kamburugamuve, Saliya Ekanayake(Authors)
    • 2021(Publication Date)
    • Wiley
      (Publisher)
    C H A P T E R 107 4 Every program that does meaningful work deals with data structures. Whether it is a large-scale distributed application or a serial program running in the cluster, we can find data structures everywhere. The simplest data types we use are primitive types such as integers and doubles. Computers are designed to work on such fundamental data by loading them into special hardware units inside CPUs called registers wherein they make decisions and perform arithmetic operations. Utilizing simple primitive types in computing is an efficient and well- documented endeavor these days. Compilers supply excellent support to opti-mize operations involving them. But a complex program cannot rely solely on just simple types to meet its data needs. To represent complex data, composite types are created from their less complicated brethren. Examples of such are present in any programming language. In C we program with structs, while in Java or C++, we program classes to create composite types. An array is another composite data structure widely used in computing. An array has multiple values of the same type in a contiguous space in memory. The individual value of an array can be accessed using an index and can be of multiple dimensions, making it extremely efficient. When we deal with substantial amounts of data, we need to use data struc-tures that can hold them as composite forms. It all boils down to how efficient a data structure is in terms of access speed and storage. Different application classes have found certain data structures to be best suited for their use cases. Data Structures 108 Chapter 4 ■ Data Structures Application frameworks designed to work on these application classes natu-rally choose the most productive data representations. For example, big data frameworks prefer table data structures to store the data, while deep learning frameworks tend to use tensors.
  • Book cover image for: Programming in C++
    eBook - ePub

    Programming in C++

    Object Oriented Features

    • Laxmisha Rai(Author)
    • 2019(Publication Date)
    • De Gruyter
      (Publisher)
    11 Structures and Unions Only wisdom and virtue can truly win men’s devotion. – Liu Bei

    11.1 Introduction

    A structure is a user-defined data type that defines a list of variables under one name in a block of memory, allowing different variables to be accessed through a single variable. A structure can be defined by using struct keyword in C++. So far, we have understood how the variables are used to store information of different data types. However, all these variables store a single type of information, such as an integer, a floating-point number, or a character. On the other hand, the arrays store more than one elements of same data type. However, in reality, we deal with different data types, and hence cannot use same data type for everything. For example, let us consider contact details of a person, which includes:(a) his/her name that is an array of characters or a string; (b) the address that is also an array of characters; (c) the phone number that is of integer type rather than characters. Hence, to store the contact details of a person, we have to consider the use of multiple data types under a single name, such as address. We can consider another example of an item in a grocery store. Each item in the store comprises of different types of information such as item name, price, manufacturer name, and item number. The item number is usually a unique number used for billing information. All the information about an item does not belong to same data type. The item name is an array of characters; the price is a floating-point number; the dates include integers; and the item number is also an integer. The following statements show how we can individually declare these details in C++ by using different data types.
  • Book cover image for: Ivor Horton's Beginning Visual C++ 2012
    • Ivor Horton(Author)
    • 2012(Publication Date)
    • Wrox
      (Publisher)
    Chapter 7 Defining Your Own Data Types
    WHAT YOU WILL LEARN IN THIS CHAPTER:
    • How structures are used
    • How classes are used
    • The basic components of a class and how you define class types
    • How to create, and use, objects of a class
    • How to control access to members of a class
    • How to create constructors
    • The default constructor
    • References in the context of classes
    • How to implement the copy constructor
    WROX.COM CODE DOWNLOADS FOR THIS CHAPTER
    You can find the wrox.com code downloads for this chapter on the Download Code tab at www.wrox.com/remtitle.cgi?isbn=9781118368084 . The code is in the Chapter 7 download and individually named according to the names throughout the chapter.

    THE STRUCT IN C++

    This chapter is about creating your own data types to suit your particular problem. It’s also about creating objects, the building blocks of object-oriented programming. An object can seem a bit mysterious to the uninitiated, but as you will see in this chapter, an object can be just an instance of one of your own data types.
    A structure is a user-defined type that you define using the struct keyword so it is often referred to as a struct. The struct originated back in the C language, and C++ incorporates and expands on the C struct . A struct in C++ is functionally replaceable by a class insofar as anything you can do with a struct , you can also achieve by using a class; however, because Windows was written in C before C++ became widely used, the struct appears pervasively in Windows programming. It is also widely used today, so you really need to know something about structs. You’ll first take a look at (C-style) structs in this chapter before exploring the more extensive capabilities offered by classes.

    What Is a struct?

    Almost all the variables that you have seen up to now have been able to store a single type of entity — a number of some kind, a character, or an array of elements of the same type. The real world is a bit more complicated than that, and just about any physical object you can think of needs several items of data to describe it even minimally. Think about the information that might be needed to describe something as simple as a book. You might consider title, author, publisher, date of publication, number of pages, price, topic or classification, and ISBN number, just for starters, and you can probably come up with a few more without too much difficulty. You could specify separate variables to contain each of the parameters that you need to describe a book, but ideally, you would want to have a single data type, BOOK , say, which embodied all of these parameters. I’m sure you won’t be surprised to hear that this is exactly what a struct
  • Book cover image for: Ivor Horton's Beginning Visual C++ 2008
    • Ivor Horton(Author)
    • 2011(Publication Date)
    • Wrox
      (Publisher)
    Chapter 7 Defining Your Own Data Types
    This chapter is about creating your own data types to suit your particular problem. It's also about creating objects, the building blocks of object-oriented programming. An object can seem a bit mysterious to the uninitiated but, as you will see in this chapter, an object can be just an instance of one of your own data types.
    In this chapter, you will learn about:
    • Structures and how they are used
    • Classes and how they are used
    • The basic components of a class and how you define class types
    • Creating and using objects of a class
    • Controlling access to members of a class
    • Constructors and how to create them
    • The default constructor
    • References in the context of classes
    • The copy constructor and how it is implemented
    • How C++/CLI classes differ from native C++ classes
    • Properties in a C++/CLI class and how you define and use them
    • Literal fields and how you define and use them
    • initonly fields and how you define and use them
    • What a static constructor is
    The struct in C++
    A structure is a user-defined type that you define using the keyword struct , so it is often referred to as a struct. The struct originated back in the C language, and C++ incorporates and expands on the C struct . A struct in C++ is functionally replaceable by a class insofar as anything you can do with a struct you can also achieve by using a class; however, because Windows was written in C before C++ became widely used, the struct appears pervasively in Windows programming. It is also widely used today, so you really need to know something about structs . We'll first take a look at (C-style) struct s in this chapter before exploring the more extensive capabilities offered by classes.
    What Is a struct?
    Almost all the variables that you have seen up to now have been able to store a single type of entity—a number of some kind, a character, or an array of elements of the same type. The real world is a bit more complicated than that, and just about any physical object you can think of needs several items of data to describe it even minimally. Think about the information that might be needed to describe something as simple as a book. You might consider title, author, publisher, date of publication, number of pages, price, topic or classification, and ISBN number just for starters, and you can probably come up with a few more without too much difficulty. You could specify separate variables to contain each of the parameters that you need to describe a book, but ideally you would want to have a single data type, BOOK say, which embodied all of these parameters. I'm sure you won't be surprised to hear that this is exactly what a struct
  • Book cover image for: Embedded Microcontroller Interfacing for M-COR ® Systems
    • G. Jack Lipovski, J. David Irwin(Authors)
    • 2000(Publication Date)
    • Academic Press
      (Publisher)
    Some C compilers will give an error message when you assign an integer to a pointer. If that occurs, you have to use a cast. Write p = (int *) 0x4000; to tell the compiler 0x4000 is really a pointer value to an integer and not an integer itself. Finally a comment is anything enclosed by /'*' and */, or anything after//. Comments can be put anywhere in your program, except within quotation marks. We strongly encourage you to supply comments to document your code. 2.2 Data Structures Data structures are at least as important as programming techniques, for if the program is one-half of the software, the data and their structure are the other half. When we discuss storage density as an architecture characteristic, we discuss only the 48 Chapter 2 Programming In C and C + + amount of memory needed to store the program. We are also concerned about data storage and its impact on static and dynamic efficiency, as well as the size of memory needed to store the data. Prudent selection of the data structures a program uses can shorten or speed up the program. These considerations of data structures are critical in microcontrollers. A data structure is one among three views of data. The information structure is the view of data the end user sees. For instance, the end user may think of his of her data as a table, such as Table 2.1 in this book. The programmer sees the same data as the data structure: strongly related to the way the data are accessed but independent of details such as size of words and position of bits. It is rather Uke a painter's template, which can be filled in with different colors. So the data structure may be an array of characters that spell out the words in Table 2.1. The storage structure is the way the information is actually stored in memory, right down to the bit positions. Therefore the table may appear as an array of 8-bit words in the storage structure. Practical engineers often find data structures hard to accept.
  • Book cover image for: Ivor Horton's Beginning Visual C++ 2013
    • Ivor Horton(Author)
    • 2014(Publication Date)
    • Wrox
      (Publisher)
    7 Defining Your Own Data Types WHAT YOU WILL LEARN IN THIS CHAPTER: ➤ How structures are used ➤ How classes are used ➤ The basic components of a class and how you define class types ➤ How to create and use objects of a class ➤ How to control access to members of a class ➤ How to create constructors ➤ The default constructor ➤ References in the context of classes ➤ How to implement the copy constructor WROX.COM CODE DOWNLOADS FOR THIS CHAPTER You can find the wrox.com code downloads for this chapter on the Download Code tab at www.wrox.com/go/beginningvisualc . The code is in the Chapter 7 download and individu-ally named according to the names throughout the chapter. THE STRUCT IN C++ This chapter is about creating your own data types to suit your particular problem. It’s also about creating objects, the building blocks of object-oriented programming. An object can seem a bit mysterious at first, but as you’ll see in this chapter, an object can be just an instance of one of your own data types. A structure is a user-defined type that you define using the struct keyword so it is often referred to as a struct . The struct originated back in C and C++ incorporates and expands on the C struct . A struct in C++ is functionally replaceable by a class insofar as anything you 268 ❘ CHAPTER 7 DEFINING YOUR OWN DATA TYPES can do with a struct , you can also achieve by using a class. However, because Windows was writ-ten in C before C++ became widely used, the struct appears pervasively in Windows programming. It is also used today, so you really need to know something about structs. You’ll first look at structs before exploring the more extensive capabilities offered by classes. What Is a struct? Almost all the variables that you have seen up to now have been able to store a single type of entity — a number of some kind, a character, or an array of elements of the same type.
  • Book cover image for: Advanced Programming with Microsoft QuickC
    SECTION Data Structures Developing techniques for representing information in a program is both a science and an art. To create programs for solving real-world problems, we must constantly be on the lookout for methods of representing data. The tools we use for representing data are commonly called data structures, and without them, our programs would be about as functional as houses without closets, cabinets, and garages. As programs become more complex and their execution speed becomes more critical, it becomes essential that we use the most efficient data structures possible. Fortunately, QuickC is an ideal language for building powerful and versatile data structures. In Section 2, we'll explore many techniques for developing useful data structures with QuickC. We'll look at both static data structures—structures that do not change during program execution—and dynamic data structures— structures that can grow and shrink as a program is executed. Designing the best data structure for an application is often the key to programming success. To help you construct both basic and complex data structures, and select the best data structure for an application, this section takes you through the step-by-step process of developing, using, debugging, and modifying data structures. In the third chapter, we'll start with the basic building blocks, and then we'll present 57 2 some useful techniques for representing static data. We'll also cover in detail the techniques for building dynamic linked lists. In Chapter 4, we'll turn our attention to doubly linked lists, stacks, and queues. As a bonus, we'll develop a general purpose string list package which provides a complete set of string processing features. To round out Section 2, we'll examine binary trees and develop an expression evaluator program that employs many of the data structures developed throughout this section.
  • Book cover image for: Basic Computation and Programming with C
    typedef statement does not create new data type; it renames any existing datatype. Basic Computation and Programming with C 448 Arrow operator( -> ) is used to access the member elements of a structure when it will be accessed by pointer. A structure can define bit-field which is a set of adjacent bits. Bit fields are used for efficient memory management. Members of Union share the same storage. Enumerated data type is used to create named integer constants. Structure, Union, Enumerated data type all are user-defined data types. R EVIEW E XERCISES 1. What are the user defined data types? Explain briefly. 2. Which of the user defined data types store(s) different types of data in a single location? 3. What is structure? How a structure member accessed? 4. What is an array of structures described with an example? 5. What is the difference between arrays within a structure and the array of structure? 6. What is the difference between array and structure? 7. How the structure members are accessed with the corresponding pointer variable? 8. What is union? How a union member accessed? 9. Compare and contrast between structure and union in C. 10. What is the importance of typedef statement? 11. What is enumeration variable? What is the advantage of using enumeration variable? 12. Define a structure Account containing account number, Customer’s name, Branch name and balance amount. Write a program to store the information of bank account holders and prints the list of customers for the given branch. 13. Define a structure Product containing Product Code, Description, Unit of measurement, Balance quantity and reorder level. Using this structure write a function that will display the list of items whose balance quantity is less than its reorder level. 14. Define a structure complex that would contain two parts – real and imaginary. Write a menu driven program to perform the following tasks: a. Add two complex numbers. b. Subtract one complex number from another.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.