Download Structures and Pointers in C: Understanding Struct Declarations, Access, and Linked Lists and more Summaries Object Oriented Programming in PDF only on Docsity!
Pointers III: Struct & Pointers
Structures
• What is a structure?
- One or more values, called members, with possibly dissimilar
types that are stored together.
- Used to group together different types of variables under the
same name.
- Aggregates a fixed set of labeled objects, possibly of different
types, into a single object (like a record)
• What is a structure NOT?
- Since members are NOT the same type/size, they are not as
easy to access as array elements that are the same size.
- Structure variable names are NOT replaced with a pointer in an
expression (like arrays)
- A structure is NOT an array of its members so can NOT use
subscripts.
Structure Declarations
struct tag {member_list} variable_list;
struct S {
int a;
float b;
} x;
struct {
int a;
float b;
} z;
struct S y;
struct S {
int a;
float b;
struct S;
Declares x to be a structure having two members, a and b. In addition, the structure tag S is created for use in future declarations. Omitting the tag field; cannot create any more variables with the same type as z Incomplete declaration which informs the compiler that S is a structure tag to be defined later Omitting the member list declares another structure variable y with the same type as x Omitting the variable list defines the tag S for use in later declarations
Structure Declarations (cont)
• So tag, member_list and variable_list are all optional,
but cannot all be omitted; at least two must appear for
a complete declaration.
struct {
int a;
char b;
float c;
} x;
struct {
int a;
char b;
float c;
} y[20], *z;
Single variable x contains 3 members
An array of 20 structures (y); and
A pointer to a structure of this type (z)
Structs on the left are treated different
by the compiler
DIFFERENT TYPES
i.e. z = &x is ILLEGAL
Typedefs è^ typedef ;
- Ex1:
- #define true 1
- #define false 0
- typedef int bool;
- bool flag = false;
- Ex2:
- char *ptr_to_char; // new variable
- typedef char * ptr_to_char; // new type
- ptr_to_char a; // new variable
Using typedefs with Structures
• A typedef statement introduces a shorthand name for
a type. The syntax is...
- typedef ;
- shorter to write
- can simplify more complex type definitions
typedef struct {
int a;
char b;
float c;
} Simple;
So è^ *Simple x; Simple y[20], z; Now x, y, and z are all the same TYPE. Similar to è^ *int x; int y[20], z;
Structures and Pointers
#include<stdio.h> typedef struct { char *name; int number; } TELEPHONE; int main() { TELEPHONE index; TELEPHONE *ptr_myindex; ptr_myindex = &index; ptr_myindex->name = "Jane Doe"; ptr_myindex->number = 12345; printf("Name: %s\n", ptr_myindex->name); printf("Telephone number: %d\n", ptr_myindex->number); return 0; } What is going on here? Remember: TELEPHONE is a type of structure;
Structures and Pointers
#include<stdio.h> #include <stdlib.h> typedef struct rec { int i; float PI; char A; } RECORD; int main() { RECORD ptr_one; ptr_one = (RECORD ) malloc (sizeof(RECORD)); (ptr_one).i = 10; (ptr_one).PI = 3.14; (ptr_one).A = 'a'; printf("First value: %d\n",(ptr_one).i); printf("Second value: %f\n", (ptr_one).PI); printf("Third value: %c\n", (ptr_one).A); free(ptr_one); return 0; } struct rec *ptr_one; ptr_one =(struct rec *) malloc (sizeof(struct rec)); ptr_one->i = 10; ptr_one->PI = 3.14; ptr_one->A = 'a'; printf("First value: %d\n", ptr_one->i); printf("Second value: %f\n", ptr_one->PI); printf("Third value: %c\n", ptr_one->A); “rec” is not necessary for given/left code, but is necessary for below code update For below, without RECORD, warning: useless storage class specifier in empty declaration
Structures and Pointers
• offsetof àtells you the offset of a variable
within a structure (stddef.h)
• should set "pb" to be a pointer to
member “b” within structure “mystruct".
struct mystruct { int a; char b; } ; //note: could put st here instead struct mystruct st; char pb = (char)&st + offsetof(struct mystruct, b);*
Self-Referential Structures
• Illegal - infinite
struct SELF_REF { int a; struct SELF_REF b; int c; } ;
Correction
struct SELF_REF { int a; struct SELF_REF *b; int c; } ;
Watch out
typedef struct { int a; struct SELF_REF *b; int c; } SELF_REF ;
Correction
typedef struct SELF_REF_TAG { int a; struct SELF_REF_TAG *b; int c; } SELF_REF ;
Structures as Function arguments
• Legal to pass a structure to a function similar to
any other variable but often inefficient
/* electronic cash register individual transaction receipt */ #define PRODUCT_SIZE 20; typedef struct { char product[PRODUCT_SIZE]; int qty; float unit_price; float total_amount; } Transaction; void print_receipt (Transaction trans) { printf(“%s\n, trans.product); printf(%d @ %.2f total %.2f\n”, trans.qty, trans.unit_price, trans.total_amount); } Function call: print_receipt(current_trans); Copy by value copies 32 bytes to the stack which can then be discarded later Instead… *(Transaction trans) trans->product // fyi: (trans).product trans->qty trans->unit_price trans->total_amount print_receipt(¤t_trans); void print_receipt(Transaction trans)
Struct storage issues
• A struct declaration consists of a list of fields,
each of which can have any type. The total
storage required for a struct object is the sum
of the storage requirements of all the fields,
plus any internal padding.
Dynamic Memory Allocation (again?!)
- Dynamic allocation allows a program to create space for a structure whose size isn’t known until runtime. - memory is more explicitly (but more flexibly) managed, typically, by allocating it from the heap , an area of memory structured for this purpose.
- The malloc and calloc functions both allocate memory and return a void pointer to it; NULL is returned if the requested allocation could not be performed (in stdlib.h)… MUST check for this! - malloc - Argument: # of bytes needed - Leaves the memory uninitialized - calloc - Arguments: number of elements AND the size of each element - Initializes the memory to zero before returning
- The free function
- You may not pass a pointer to this function that was not obtained from an earlier call to malloc/calloc.
- Memory must not be accessed after it has been freed.
- Memory Leaks
- Memory that has been dynamically allocated but has not been freed and is no longer in use.
- Negative because it increases the size of the program and lead to problems.
DMA Example
int *pi_save, *pi; pi = malloc(20); if (pi == NULL) { printf(“Out of memory!\n”); exit(1); } for (int x = 0; x < 5; x +=1) *pi++ = 0; // print
Set each element of the newly allocated integer array of five
elements to zero
QUESTIONS
- What are the values in the new memory before initializing to zero?
- Where is pi pointing to after the for loop?
- What does the print loop look like?
- How update to use calloc?
- How free the memory?