C Programming: Structures

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Which of the following is the primary purpose of a structure in C programming?

  • To implement object-oriented programming principles such as inheritance and polymorphism.
  • To create dynamic arrays that can grow or shrink during program execution.
  • To define a new data type that groups different data types into a single unit. (correct)
  • To manage memory allocation and deallocation for primitive data types.

In C, what are the three different methods to define a structure?

  • Variable, tagged, and type-defined structures (correct)
  • Simple, complex, and nested structures
  • Global, local, and static structures
  • Public, private, and protected structures

What is the main difference between a 'variable structure' and a 'tagged structure' in C?

  • A variable structure cannot contain pointers, while a tagged structure can.
  • A variable structure defines a type, while a tagged structure defines a struct variable.
  • A variable structure must be defined before it is used, while a tagged structure can be defined anywhere in the code.
  • A variable structure definition defines a struct variable, while a tagged structure definition defines a type. (correct)

What is the primary advantage of using a 'typedef structure' in C?

<p>It allows the definition of variables without using the <code>struct</code> keyword. (C)</p>
Signup and view all the answers

How do you access members of a structure in C using the dot operator?

<p><code>structure_name.member_name</code> (A)</p>
Signup and view all the answers

When should you use the arrow operator (->) instead of the dot operator (.) to access structure members in C?

<p>When you have a pointer to a structure. (C)</p>
Signup and view all the answers

What is a 'nested structure' in C?

<p>A structure containing a member that is another structure. (D)</p>
Signup and view all the answers

When initializing a structure in C, what is the significance of the order in which the values are provided?

<p>The order is essential because the values are assigned to the members in the order they are declared in the structure. (D)</p>
Signup and view all the answers

In C, what happens if you provide fewer initializers than members when initializing a structure?

<p>The remaining members are initialized to 0 for primitive types. (B)</p>
Signup and view all the answers

Why should the sizeof() operator be used when dynamically allocating storage for structures?

<p>To ensure that the correct amount of memory is allocated for the structure, regardless of the compiler or platform. (C)</p>
Signup and view all the answers

What is the significance of using calloc() instead of malloc() when allocating memory for an array of structures?

<p><code>calloc()</code> automatically initializes the memory to zero, while <code>malloc()</code> does not. (D)</p>
Signup and view all the answers

In C, what is the primary method for passing an array by value into a function?

<p>Embed the array within a structure and pass the structure. (B)</p>
Signup and view all the answers

Consider the scenario where a large structure is passed by value to a function. What is a potential disadvantage of this approach?

<p>It may cause a stack overflow due to copying the entire structure onto the stack. (D)</p>
Signup and view all the answers

When passing a structure as a parameter to a function by value, what happens to the original structure in the calling function?

<p>The original structure is copied to the stack, and the function operates on the copy. (B)</p>
Signup and view all the answers

What is the advantage of passing a structure pointer as a parameter to a function instead of passing the structure by value?

<p>It avoids copying the entire structure, making it more efficient. (D)</p>
Signup and view all the answers

If you want to prevent a function from modifying a structure passed as a parameter, how can you achieve this?

<p>Use the <code>const</code> modifier when declaring the structure parameter. (D)</p>
Signup and view all the answers

What is a potential issue when a function returns a pointer to a local structure variable?

<p>The structure will be automatically deallocated after the function returns, leading to a dangling pointer. (A)</p>
Signup and view all the answers

What is a safer alternative to returning a pointer to a local structure variable from a function?

<p>Return the structure by value. (C)</p>
Signup and view all the answers

What is a potential drawback of returning a structure by value from a function?

<p>It may be inefficient due to copying a potentially large structure. (D)</p>
Signup and view all the answers

How can the disadvantage of copying a large structure on returning it from a function be avoided?

<p>By returning a pointer to the structure. (C)</p>
Signup and view all the answers

In C, what happens when an array is passed as a parameter to a function?

<p>A pointer to the first element of the array is passed. (C)</p>
Signup and view all the answers

What is the only way to return an array from a function by value in C?

<p>By embedding it in a structure. (D)</p>
Signup and view all the answers

What is the main difference between passing an array as a parameter and embedding it in a structure when passing it as a parameter?

<p>Passing an array simulates pass by reference, while embedding provides a true pass by value. (A)</p>
Signup and view all the answers

What is the major problem in embedding an arbitrarily huge array inside a structure and passing it around?

<p>Copying such structures becomes extremely expensive. (B)</p>
Signup and view all the answers

Which of the following declares a structure named car with members model (string) and year (integer)?

<pre><code class="language-c">struct car { char model[50]; int year; }; ``` (A) </code></pre>
Signup and view all the answers

Given a structure struct Point { int x, y; }, how do you declare a variable p of this type and initialize its members to x=10 and y=20?

<p><code>struct Point p = { 10, 20 };</code> (D)</p>
Signup and view all the answers

Assuming you have a structure typedef struct { int id; char name[50]; } Person;, how would you dynamically allocate memory for a single Person?

<p><code>Person* ptr = (Person*) malloc(sizeof(Person));</code> (A)</p>
Signup and view all the answers

If you have a pointer Person* ptr to a Person structure (defined as typedef struct { int id; char name[50]; } Person;), how would you access the id member?

<p>Both B and C (B)</p>
Signup and view all the answers

What is the purpose of using typedef with structures in C?

<p>To create a new name (alias) for the structure type, simplifying its use. (C)</p>
Signup and view all the answers

Consider you have the following code:

struct Point {
 int x, y;
};

void printPoint(struct Point p) {
 p.x = 100;
 printf("%d, %d\n", p.x, p.y);
}

int main() {
 struct Point myPoint = {10, 20};
 printPoint(myPoint);
 printf("%d, %d\n", myPoint.x, myPoint.y);
 return 0;
}

What will be printed to the console?

<p><code>100, 20\n10, 20</code> (B)</p>
Signup and view all the answers

Flashcards

What is a Structure?

A structure is a user-defined data type that combines different data types into a single unit.

What is a variable structure?

A way to define a structure where a structure variable is defined directly with the struct keyword.

What is a Tagged Structure?

A structure definition that associates a name (tag) with the structure, allowing reuse.

What is a Typedef Structure?

A structure definition using 'typedef' to create a new type name for the structure.

Signup and view all the flashcards

What is the Dot Operator?

The (.) operator in C facilitates access to members within a structure.

Signup and view all the flashcards

What is the Arrow Operator?

The (->) operator accesses structure members through a pointer.

Signup and view all the flashcards

What are Nested Structures?

A structure that contains another structure as one of its members.

Signup and view all the flashcards

Initializing Structures

Structures can be initialized with values upon declaration; order matters.

Signup and view all the flashcards

Dynamic Allocation and sizeof()

The sizeof() operator determines the size needed for dynamic allocation of the structure.

Signup and view all the flashcards

Arrays within Structures

A structure member can be of an array type.

Signup and view all the flashcards

Arrays of Structures

An array where each element is a structure.

Signup and view all the flashcards

Structures as Parameters (by value)

A function receives a copy of the entire structure, not the original.

Signup and view all the flashcards

Structure Pointers as Parameters

Passing a structure pointer to a function is more efficient, allowing modifications to the original structure.

Signup and view all the flashcards

Const Struct Parameter

Using const prevents modification of the structure by the function.

Signup and view all the flashcards

Returning Structure Pointer to Local Variable

Returning a structure pointer to a local variable is dangerous, as the memory may be invalid after the function ends.

Signup and view all the flashcards

Function Return Structure Values

Returning a structure by value copies the structure, avoiding pointer issues, but can be inefficient for large structures.

Signup and view all the flashcards

Arrays as Parameters & Return

Arrays cannot be directly passed or returned; embed in a structure.

Signup and view all the flashcards

Study Notes

  • Structures are new data types that combine different types into a single, compound data type.
  • Struct definitions are analogous to templates or blueprints and composed of members of previously defined types.
  • Structures must be defined before they are used.
  • C has three different methods to define a structure: variable structures, tagged structures, and type-defined structures.

Struct Variable

  • A variable structure definition defines a struct variable.
  • An example is struct { double x; double y; } point; where x and y are member names and point is the variable name.
  • Keep in mind the semicolon at the end of the definition.

Tagged Structure

  • A tagged structure definition defines a type which can be used to define variables, parameters, and return types.
  • For example: struct point_t { double x; double y; }; The point_t is the structure tag.
  • Variable definitions using the tag looks like this: struct point_t point1, point2, point3;
  • point1, point2, and point3 all have members x and y.

Typedef Structure

  • A type-defined structure allows the definition of variables without the struct keyword, where tagged are used to define varaibles, parameters, and return types.
  • A structure looks like this: typedef struct { long ssn; int empType; float salary; } employee_t; where employee_t is new type name.
  • A variable definition looks like this: employee_t emp;
  • Variable emp has members ssn, empType, and salary.

Dot Operator

  • The dot operator is used to access member variables with a syntax of structure_variable_name.member_name.
  • Accessed variables act like other variables.
  • Given struct point_t { double x; double y; };, you can access the variables like this:
void setPoints() {
  struct point_t point1, point2;
  point1.x = 7;  // initialize point1 members
  point1.y = 11;
  point2 = point1;  // copy point1 to point2
}

Arrow Operator

  • The arrow operator is used to access member variables using a pointer.
  • The arrow operator syntax is structure_variable_pointer->member_name.
  • The dot operator syntax can also be used like this: (*structure_variable_pointer).member_name
  • Given typedef struct { long ssn; int empType; float salary; } employee_t; the following code initializes the variables:
employee_t *newEmp (long n, int type, float sal) {
  employee_t *empPtr = malloc(sizeof(employee_t));
  empPtr->ssn = n;  // -> operator
  empPtr->empType = type;  // -> operator
  (*empPtr).salary = sal;  // dot operator
  return empPtr;
}

Nested Structures

  • A member that is of a structure type is considered nested.
  • Example:
typedef struct {
  int month;
  int day;
  int year;
} date_t;

typedef struct {
  double height;
  int weight;
  date_t birthday;
} personInfo_t;
  • personInfo_t person; defines a variable of type personInfo_t.
  • person.birthday is a member of person, and person.birthday.year is a member of person.birthday.

Initializing Structures

  • Structures may be initialized at the time they are declared.
  • Order is essential; the sequence of values initializes successive variables in the struct.
  • It is an error to pass more initializers than members.
  • If fewer initializers than members are provided, the initializers provided are used to initialize the data members; the remainder are initialized to 0 for primitive types.
  • Given this structure:
typedef struct {
  int month;
  int day;
  int year;
} date_t;
  • It can be initialized like this: date_t due_date = {12, 31, 2020};

Dynamic Allocation of Structures

  • The sizeof() operator should always be used in dynamic allocation of storage for structured data types, as well as reading and writing structured data types.
  • Example:
typedef struct {
  int month;
  int day;
  int year;
} date_t;
date_t due_date;

int date_t_len = sizeof(date_t);  // sizeof type
int due_date_len = sizeof(due_date);  // sizeof variable

printf("sizeof(date_t)=%d\n", date_t_len);
printf("sizeof(due_date)=%d\n", due_date_len);

date_t *due_dates = calloc(100, sizeof(date_t));
  • The sizeof(date_t) and sizeof(due_date) both equal 12.

Arrays within Structures

  • A member of a structure may be an array.
  • Example:
typedef struct {
  long ssn;  // SSN
  double payRate;  // Hourly rate
  float hoursWorked[7];  // Daily hours worked Sun-Sat
} timeCard_t;

timeCard_t empTime;
empTime.hoursWorked[5] = 6.5;  // Thur hours worked

Arrays of Structures

  • An array of structure types can be created.
  • Example:
typedef struct {
  // unsigned char will hold 0-255
  unsigned char red;
  unsigned char green;
  unsigned char blue;
} pixel_t;

pixel_t pixelMap[800][600];

pixelMap[425][37].red = 127;
pixelMap[425][37].green = 0;
pixelMap[425][37].blue = 58;

Array of Structures Containing Arrays

  • Arrays of structures can contain arrays
typedef struct {
  long ssn;            // SSN
  double payRate;      // Hourly rate
  float hoursWorked[7];  // Daily hours worked Sun-Sat
} timeCard_t;
timeCard_t empTime[1000];
// Thur hours worked, emp # 10
empTime[9].hoursWorked[5] = 6.5;

Structures as Parameters

  • A struct, like an int, may be passed to a function.
  • The process of passing a struct to a function works like passing an int: the complete structure is copied to the stack, and the called function is unable to modify the caller's copy of the variable.
  • Example:
typedef struct {
  double x;  // x coordinate
  double y;  // y coordinate
} point_t;

void changePoint(point_t p) {
  printf("x=%.1lf, y=%.11f\n", p.x, p.y);  // x=1.2, y=2.3
  // p.x = 3.4;
  // p.y = 4.5;
}

void mainPoint() {
  point_t point = {1.2, 2.3};
  changePoint(point);
  printf("x=%.1lf, y=%.1lf\n", point.x, point.y);  // x=1.2, y=2.3
}
  • A disadvantage of passing structures this way is it's inefficient, potentially causing stack overflow, when copying large structures onto the stack.
  • This is especially true for structures like this example which contains 1 billion integers:
typedef struct {
  int w[1000 * 1000 * 1000];  // One billion int elements
} big_t;

Structure Pointers as Parameters

  • Passing structure pointers is more effective as passing an address only pushes a single word on the stack.
  • The called function can then modify the structure.
  • Example:
typedef struct {
  double x;  // x coordinate
  double y;  // y coordinate
} point_t;

void changePoint(point_t *p) {
  printf("x=%.1lf, y=%.1lf\n", p->x, p->y);  // x=1.2, y=2.3
  // p->x = 3.4;
  // p->y = 4.5;
}

void mainPoint() {
  point_t point = {1.2, 2.3};
  changePoint(&point);
  printf("x=%.1lf, y=%.1lf\n", point.x, point.y);  // x=3.4, y=4.5
}

Const Struct Parameter

  • If you do not want the recipient to modify the structure, use the const modifier: (const point_t * p)

Return Structure

  • Scalar values (int, float, etc.) are efficiently returned in CPU registers.
  • Historically, structure assignments and the return of structures were not supported in C.
  • The return of pointers (addresses), including pointers to structures, has always been supported.

Return Structure Pointer to Local Variable

  • Returning a pointer to a variable that was allocated on the stack during execution of the function is risky.
  • Such variables are subject to being wiped out by subsequent function calls.
  • It is possible for a function to return a structure, depending on the structure assignment mechanisms that copy one complete structure to another which avoids returning a function.
  • This can incur a possible extreme penalty of copying a very large structure

Arrays as Parameters & Return

  • An arrays address is passed as a parameter, simulating passing by reference.
  • Embedding an array in a structure is the only way to pass an array by value.
  • Embedding in a structure is also the only way to return an array.
  • Both passing and returning arrays involves copying and must be mindful of size.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

Programming in C: Structures

More Like This

Estruturas (structs) em C
19 questions

Estruturas (structs) em C

GraciousTriumph6829 avatar
GraciousTriumph6829
CSIT 231: Function Pointers and Structs
45 questions
Use Quizgecko on...
Browser
Browser