0% found this document useful (0 votes)
28 views

Chap II. Complex Data Types

pmovie->title To access the title member of the object that pmovie points to. This is equivalent to (*pmovie).title but using the arrow operator makes the code more readable. So in summary, the arrow operator: - Is used with pointers to objects with members (structures, classes, etc.) - Provides access to the members of the object the pointer refers to - Is equivalent to (*pointer).member - Makes the code more readable than using explicit dereferencing

Uploaded by

thierrymuhirwa5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Chap II. Complex Data Types

pmovie->title To access the title member of the object that pmovie points to. This is equivalent to (*pmovie).title but using the arrow operator makes the code more readable. So in summary, the arrow operator: - Is used with pointers to objects with members (structures, classes, etc.) - Provides access to the members of the object the pointer refers to - Is equivalent to (*pointer).member - Makes the code more readable than using explicit dereferencing

Uploaded by

thierrymuhirwa5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Complex Data Types

• In C(++), it exist way to combine fundamental types to form


more complex ones.

• Complex types:
 Pointers
 Arrays
 structures and Union

1
Pointers
• Each program variable is stored in the computer’s memory at
some location, or address.
• A pointer is a variable that holds the value of such an address.
Given a type T, the type T* denotes a pointer to a variable of type T. For
example, int* denotes a pointer to an integer.
• Two essential operators are used to manipulate pointers. The
first returns the address of an object in memory, and the second returns
the contents of a given address.
The first task is performed by the address-of operator, &.
For example if x is an integer variable in your program &x is the
address of x in memory.
Accessing an object’s value from its address is called
dereferencing. This is done using the * operator.
2
Pointers: example
• In the code fragment below, the variable p is declared to be a
pointer to a char, and is initialized to point to the variable ch.
Thus, *p is another way of referring to ch. Observe that when
the value of ch is changed, the value of *p changes as well.

char ch = ’Q’;
char* p;
p = &ch; // p holds the address of ch
printf("%c", *p); // outputs the character ’Q’
ch = ’Z’; // ch now holds ’Z’
printf("%c", *p); // outputs the character ’Z’
*p = ’X’; // ch now holds ’X’
printf("%c", ch); // outputs the character ’X’

3
Pointers declaration
• (Data type) + ( *) + (Variable name),
• But be careful! The “*” operator binds with the variable
name, not with the type name.
• Example: int* x, y, z; // same as: int* x; int y; int z;
 The example declares one pointer variable
x, but the other two variables are plain integers.
• The simplest way to avoid the confusion is to declare one
variable per statement.

4
Arrays
• An array is a collection of elements of the same
type.
• Given any type T and a constant N, a variable of
type T[N] holds an array of N elements, each of type T.
• Each element of the array is referenced by its index,
that is, a number from 0 to N − 1.

double f [5]; // array of 5 doubles: f[0], . . ., f[4]


int m[10]; // array of 10 ints: m[0], ..., m[9]
f[4] = 2.5;
m[2] = 4;
printf("%f", f[m[2]]); // outputs f[4], which is 2.5

5
Arrays (cont.)
• Once declared, it is not possible to increase
the number of elements in an array.
• Also, C(++) provides no built-in run-time checking for array
subscripting out of bounds.
• A two-dimensional array is implemented as an
“array of arrays.” For example: “
 int A[15][30]”
 declares A to be an array of 15 objects, each of which is an
array of 30 integers. An element in such an array is indexed
as A[i][j], where i is in the range 0 to 14 and j is in the range
0 to 29.
6
Array Declaration
• Two ways:
 Data type + Variable name + [size of the array]
 Data type + Variable name +[ ] = {element1, …, elementn}
Examples:

double f [5]; //declare array f[5]


int a[ ] = {10, 11, 12, 13}; // declares and initializes a[4]
char c[ ] = {’c’, ’a’, ’t’}; // declares and initializes c[3]

• Just as it is possible to declare an array of integers, it is possible to


declare an array of pointers to integers. For example, int* r[17] declares
an array r consisting of 17 pointers to objects of type int

7
Pointers and Arrays
• There is an interesting connection between arrays and pointers:
The name of an array is
equivalent to a pointer to the array’s initial element and vice versa
char c[] = {’c’, ’a’, ’t’};

char* p = c; // p points to c[0]

char* q = &c[0]; // q also points to c[0]

//printf("%c%c%c", c[2], p[2], q[2]); // outputs “ttt”

8
Strings
• A string literal, such as "Hello World", is represented as a fixed-length
array of characters that ends with the null character.

9
Strings: example(1/2)
• STL strings may be concatenated using the + operator, they may be
compared with each other using lexicographic (or dictionary) order, and
they may be input and output using the printf () and scanf() functions,
respectively.

For example:

#include <string>
include<stdio.h>;
// ...
Char s[] = "to be"; -------- char s[?]
string t = "not " + s; // t = “not to be”
string u = s + " or " + t; // u = “to be or not to be”
if (s > t) // true: “to be” > “not to be”
printf("%s", u); // outputs “to be or not to be”

• There are other STL string operations that we will discuss later
10
Strings: example(2/2)
• We can append one string to another using the += operator.
• Also, strings may be indexed like arrays and the number of characters in a
string s is given by s.size().
• Some examples:

• The C++ STL provides many other string operators including operators for

extracting, searching for, and replacing substrings. We discuss some of


these later.

11
User-Defined Structure Types

• A database is a collection of information subdivided into


records.
– A record is a collection of information of one data object (e.g., ID,
name, and age of a student).

• C(++) allows us to define a new data type (called structure


type) for each category of a structured data object.

12
C-Style Structures

• A structure is useful for storing an aggregation of elements.

• Unlike an array, the elements of a structure may be of different types.

• Each member, or field, of a structure is referred to by a given name.

13
C-Style Structures: example
struct Passenger {
char name[30];
int age;
char address[50];
};

• This defines a new type called Passenger. Let us declare and initialize a
variable named “pass” of this type.

struct Passenger pass = { "John ", 20, ”Huye" };

14
C-Style Structures (cont.)
• The individual members of the structure are accessed using the member
selection operator, which has the form:
struct_name.member.

• For example, we could change some of our structure’s fields as follows.


pass.name = “Peter"; // change name
pass.age= 30; // change age
• Structures of the same type may be assigned to one another. For example,

if p1 and p2 are of type Passenger, then p2 = p1 copies the elements of p1


to p2.

• What we have discussed so far might be called a C-style structure. C++


provides a much more powerful and flexible construct, a class, in which
both data and functions can be combined. We discuss classes later.
15
Pointers to structures(1/4)
• Like any other type, structures can be pointed by its own type of pointers:

struct movies_t {
char title[50];
int year;
};
movies_t amovie;
movies_t * pmovie;

Here amovie is an object of structure type movies_t, and pmovie is a pointer to


point to objects of structure type movies_t.
So, the following code would also be valid:

pmovie = &amovie;

The value of the pointer pmovie would be assigned to a reference to the object amovie (its
memory address).

16
Pointers to structures(2/4)

• We will now go with another example that includes pointers, which will
serve to introduce a new operator:
the arrow operator (->):

#include <stdio.h>
struct movies_t {
string title;
int year;
}; printf(" \nYou have entered:\n ");
int main () printf(" %s\n", pmovie->title );
{ printf(" %d\n", pmovie->year);
//string mystr;
movies_t amovie;
movies_t * pmovie;
pmovie = &amovie;
printf(" enter the title
scanf(“%s“, pmovie->title);
printf(" Enter year: ");
scanf(“%d“, pmovie->year);

17
Pointers to structures(3/4)
• The previous code includes an important introduction: the arrow operator (->). This is a
dereference operator that is used exclusively with pointers to objects with members. This
operator serves to access a member of an object to which we have a reference. In the
example we used:

pmovie->title
Which is for all purposes equivalent to:
(*pmovie).title
• Both expressions pmovie->title and (*pmovie).title are valid and both mean that
we are evaluating the member title of the data structure pointed by a pointer called
pmovie. It must be clearly differentiated from:
*pmovie.title which is equivalent to: *(pmovie.title)

And that would access the value pointed by a hypothetical pointer member called title of the
structure object pmovie (which in this case would not be a pointer).

18
Pointers to structures(4/4)
The following panel summarizes possible combinations of pointers and structure members:

19
UNION
• Only one element in the union may have a value set at any given time
• Everything we have shown you for structures will work for unions, except for
setting more than one of its members at a time
 Unions are mainly used to conserve memory
• While each member within a structure is assigned its own unique storage area,
the members that compose a union share the common storage area within the
memory

• Unions are useful for application involving multiple members where values are
not assigned to all the members at any one time

20
UNION
Example
union EmpDates
{
int nbr_working_days;
struct end_date
{
int day;
int month;
int year;
} last_day;
};

21
Union vs. Struct

• Similarities
– Definition syntax virtually identical

– Member access syntax identical

• Differences
– Members of a struct each have their own address in memory.

– The size of a struct is as big as the sum of the sizes of the members

– Members of a union share the same memory.

– The size of a union is the size of the largest member.


Sources

G. T. Michael, T. Roberto, M. M. David, Data Structures


and Algorithms in C++ ,Second Edition,2011.
Juan Soulié, C++ Language June, 2007

23
24

You might also like