0% found this document useful (0 votes)
7 views86 pages

C_programming_Chapter03_SEN2201

The document covers control flow in programming, including blocks, conditional statements, loops, and the use of goto statements, highlighting the potential for 'spaghetti code' from excessive goto usage. It also discusses standard input/output operations in C, including formatted input/output functions like printf and scanf, as well as file I/O using fopen and related functions. Additionally, it touches on command line input and the structure of the main function with arguments.

Uploaded by

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

C_programming_Chapter03_SEN2201

The document covers control flow in programming, including blocks, conditional statements, loops, and the use of goto statements, highlighting the potential for 'spaghetti code' from excessive goto usage. It also discusses standard input/output operations in C, including formatted input/output functions like printf and scanf, as well as file I/O using fopen and related functions. Additionally, it touches on command line input and the structure of the main function with arguments.

Uploaded by

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

Lecture 3

Review

Control flow

I/O
Standard I/O
String I/O
File I/O

1
Blocks

• Blocks combine multiple statements into a single unit.


• Can be used when a single statement is expected.
• Creates a local scope (variables declared inside are local
to the block).
• Blocks can be nested.

{
i n t x =0;
{
i n t y =0; / ∗ both x and y v i s i b l e ∗ /
}
/∗ only x v i s i b l e ∗/
}

1
Conditional blocks

if ... else..else if is used for conditional branching of execution


i f ( cond )
{
/ ∗ code executed i f cond i s t r u e ∗ /
}
else
{
/ ∗ code executed i f cond i s f a l s e ∗ /
}

2
Conditional blocks

switch..case is used to test multiple conditions (more efficient


than if else ladders).
switch ( o p t )
{
case ’A’ :
/ ∗ execute i f o p t == ’A ’ ∗ /
break ;
case ’B’ :
case ’C’ :
/ ∗ execute i f o p t == ’B ’ | | o p t == ’C ’ ∗ /
default :
}

3
Iterative blocks

• while loop tests condition before execution of the block.


• do..while loop tests condition after execution of the block.
• for loop provides initialization, testing and iteration together.

4
Review

Control flow

I/O
Standard I/O
String I/O
File I/O

5
goto

• goto allows you to jump unconditionally to arbitrary part of


your code (within the same function).
• the location is identified using a label.
• a label is a named location in the code. It has the same
form as a variable followed by a ’:’

start :
{
i f ( cond )
goto o u t s i d e ;
/ ∗ some code ∗ /
goto s t a r t ;
}
outside :
/∗ outside block ∗/

5
Spaghetti code

Dijkstra. Go To Statement Considered Harmful.


Communications of the ACM 11(3),1968
• Excess use of goto creates sphagetti code.
• Using goto makes code harder to read and debug.
• Any code that uses goto can be written without using one.

6
error handling
Language like C++ and Java provide exception mechanism to
recover from errors. In C, goto provides a convenient way to exit
from nested blocks.

c o n t _ f l a g =1;
for ( . . )
for ( . . ) {
{ for ( i n i t ; cont_flag ; i t e r )
for ( . . ) {
{ i f ( error_cond )
i f ( error_cond ) {
goto e r r o r ; c o n t _ f l a g =0;
/∗ skips 2 blocks ∗/ break ;
} }
} / ∗ inner loop ∗ /
error : }
i f ( ! c o n t _ f l a g ) break ;
/ ∗ outer loop ∗ /
}
7
Review

Control flow

I/O
Standard I/O
String I/O
File I/O

8
Preliminaries

• Input and output facilities are provided by the standard


library <stdio.h> and not by the language itself.
• A text stream consists of a series of lines ending with ’\n’.
The standard library takes care of conversion from
’\r\n’−’\n’
• A binary stream consists of a series of raw bytes.
• The streams provided by standard library are buffered.

8
Standard input and output

int putchar(int)
• putchar(c) puts the character c on the standard output.
• it returns the character printed or EOF on error.
int getchar()
• returns the next character from standard input.
• it returns EOF on error.

9
Standard input and output
What does the following code do?
i n t main ( )
{
char c ;
while ( ( c= g e t c h a r ( ) ) ! = EOF)
{
i f ( c>=’A’ && c<=’Z’ )
c=c−’A’+’a’ ;
putchar ( c ) ;
}
return 0;
}

To use a file instead of standard input, use ’<’ operator (*nix).


• Normal invocation: ./a.out
• Input redirection: a.out < file.txt. Treats file.txt as source of
standard input.This is an OS feature, not a language
feature.
10
Standard output:formatted

int printf (char format [], arg1,arg2 ,...)


• printf() can be used for formatted output.
• It takes in a variable number of arguments.
• It returns the number of characters printed.
• The format can contain literal strings as well as format
specifiers (starts with %).
Examples:
p r i n t f ( "hello world\n" ) ;
p r i n t f ( "%d\n" , 1 0 ) ; / ∗ f o r m a t : %d ( i n t e g e r ) , argument : 1 0 ∗ /
p r i n t f ( "Prices:%d and %d\n" , 1 0 , 2 0 ) ;

11
printf format specification
The format specification has the following components
%[flags ][ width ][. precision ][ length]<type>
type:

type meaning example


d,i integer printf ("%d",10); /∗prints 10∗/
x,X integer (hex) printf ("%x",10); /∗ print 0xa∗/
u unsigned integer printf ("%u",10); /∗prints 10∗/
c character printf ("%c",’A’); /∗prints A∗/
s string printf ("%s","hello"); /∗prints hello∗/
f float printf ("%f",2.3); /∗ prints 2.3∗/
d double printf ("%d",2.3); /∗ prints 2.3∗/
e,E float(exp) 1e3,1.2E3,1E−3
% literal % printf ("%d %%",10); /∗prints 10%∗/

12
printf format specification (cont.)

%[flags ][ width ][. precision ][ modifier]<type>


width:

format output
printf ("%d",10) "10"
printf ("%4d",10) bb10 (b:space)
printf ("%s","hello") hello
printf ("%7s","hello") bbhello

13
printf format specification (cont.)

%[flags ][ width ][. precision ][ modifier]<type>


flag:

format output
printf ("%d,%+d,%+d",10,−10) 10,+10,-10
printf ("%04d",10) 0010
printf ("%7s","hello") bbhello
printf ("%-7s","hello") hellobb

14
printf format specification (cont.)

%[flags ][ width ][. precision ][ modifier]<type>


precision:

format output
printf ("%.2f,%.0f,1.141,1.141) 1.14,1
printf ("%.2e,%.0e,1.141,100.00) 1.14e+00,1e+02
printf ("%.4s","hello") hell
printf ("%.1s","hello") h

15
printf format specification (cont.)

%[flags ][ width ][. precision ][ modifier]<type>


modifier:

modifier meaning
h interpreted as short. Use with i,d,o,u,x
l interpreted as long. Use with i,d,o,u,x
L interpreted as double. Use with e,f,g

16
Digression: character arrays

Since we will be reading and writing strings, here is a brief


digression
• strings are represented as an array of characters
• C does not restrict the length of the string. The end of the
string is specified using 0.
For instance, "hello" is represented using the array
{’h’,’e’,’l’,’l’,’\0’}.
Declaration examples:
• char str []= "hello"; /∗compiler takes care of size∗/
• char str[10]="hello"; /∗make sure the array is large enough∗/
• char str []={ ’h’,’e’,’l’,’l’,0};
Note: use \" if you want the string to contain ".

17
Digression: character arrays

Comparing strings: the header file <string .h> provides the


function int strcmp(char s[],char t []) that compares two strings in
dictionary order (lower case letters come after capital case).
• the function returns a value <0 if s comes before t
• the function return a value 0 if s is the same as t
• the function return a value >0 if s comes after t
• strcmp is case sensitive
Examples
• strcmp("A","a") /∗<0∗/
• strcmp("IRONMAN","BATMAN") /∗>0∗/
• strcmp("aA","aA") /∗==0∗/
• strcmp("aA","a") /∗>0∗/

18
Formatted input

int scanf(char∗ format ,...) is the input analog of printf.


• scanf reads characters from standard input, interpreting
them according to format specification
• Similar to printf , scanf also takes variable number of
arguments.
• The format specification is the same as that for printf
• When multiple items are to be read, each item is assumed
to be separated by white space.
• It returns the number of items read or EOF.
• Important: scanf ignores white spaces.
• Important: Arguments have to be address of variables
(pointers).

19
Formatted input

int scanf(char∗ format ,...) is the input analog of printf.


Examples:

printf ("%d",x) scanf("%d",&x)


printf ("%10d",x) scanf("%d",&x)
printf ("%f",f) scanf("%f",&f)
printf ("%s",str) scanf("%s",str) /∗note no & required∗/
printf ("%s",str) scanf("%20s",str) /∗note no & required∗/
printf ("%s %s",fname,lname) scanf("%20s %20s",fname,lname)

20
String input/output

Instead of writing to the standard output, the formatted data can


be written to or read from character arrays.
int sprintf (char string [], char format [], arg1,arg2)
• The format specification is the same as printf.
• The output is written to string (does not check size).
• Returns the number of character written or negative value
on error.
int sscanf(char str [], char format [], arg1,arg2)
• The format specification is the same as scanf;
• The input is read from str variable.
• Returns the number of items read or negative value on
error.

21
File I/O
So far, we have read from the standard input and written to the
standard output. C allows us to read data from text/binary files
using fopen().
FILE∗ fopen(char name[],char mode[])
• mode can be "r" (read only),"w" (write only),"a" (append)
among other options. "b" can be appended for binary files.
• fopen returns a pointer to the file stream if it exists or
NULL otherwise.
• We don’t need to know the details of the FILE data type.
• Important: The standard input and output are also FILE*
datatypes (stdin,stdout).
• Important: stderr corresponds to standard error
output(different from stdout).

22
File I/O(cont.)

int fclose (FILE∗ fp)


• closes the stream (releases OS resources).
• fclose() is automatically called on all open files when
program terminates.

23
File input
int getc(FILE∗ fp)

• reads a single character from the stream.


• returns the character read or EOF on error/end of file.

Note: getchar simply uses the standard input to read a


character. We can implement it as follows:
#define getchar() getc(stdin )

char[] fgets(char line [], int maxlen,FILE∗ fp)


• reads a single line (upto maxlen characters) from the input
stream (including linebreak).
• returns a pointer to the character array that stores the line
(read-only)
• return NULL if end of stream.

24
File output
int putc(int c,FILE∗ fp)
• writes a single character c to the output stream.
• returns the character written or EOF on error.
Note: putchar simply uses the standard output to write a
character. We can implement it as follows:
#define putchar(c) putc(c,stdout)

int fputs(char line [], FILE∗ fp)


• writes a single line to the output stream.
• returns zero on success, EOF otherwise.
int fscanf(FILE∗ fp,char format [], arg1,arg2)

• similar to scanf,sscanf
• reads items from input stream fp.

25
Command line input

• In addition to taking input from standard input and files, you


can also pass input while invoking the program.
• Command line parameters are very common in *nix
environment.
• So far, we have used int main() as to invoke the main
function. However, main function can take arguments that
are populated when the program is invoked.

26
Command line input (cont.)

int main(int argc,char∗ argv[])


• argc: count of arguments.
• argv[]: an array of pointers to each of the arguments
• note: the arguments include the name of the program as
well.
Examples:
• ./cat a.txt b.txt (argc=3,argv[0]="cat" argv[1]="a.txt"
argv[2]="b.txt"
• ./cat (argc=1,argv[0]="cat")

27
Review

Pointers and Memory Addresses


Physical and Virtual Memory
Addressing and Indirection
Functions with Multiple Outputs

Arrays and Pointer Arithmetic

Strings
String Utility Functions

1
Review: Unconditional jumps

• goto keyword: jump somewhere else in the same function


• Position identified using labels
• Example (for loop) using goto:
{
i n t i = 0 , n = 20; / ∗ i n i t i a l i z a t i o n ∗ /
goto loop_cond ;
loop_body :
/ ∗ body o f l o o p here ∗ /
i ++;
loop_cond :
i f ( i < n ) / ∗ loop c o n d i t i o n ∗ /
goto loop_body ;
}

• Excessive use of goto results in “spaghetti” code

1
Review: I/O Functions

• I/O provided by stdio.h, not language itself


• Character I/O: putchar(), getchar(), getc(),
putc(), etc.
• String I/O: puts(), gets(), fgets(), fputs(), etc.
• Formatted I/O: fprintf(), fscanf(), etc.
• Open and close files: fopen(), fclose()
• File read/write position: feof(), fseek(), ftell(), etc.
• ...

2
Review: printf() and scanf()

• Formatted output:
int printf (char format [], arg1, arg2, ...)
• Takes variable number of arguments
• Format specification:
%[flags][width][.precision][length]<type>
• types: d, i (int), u, o, x, X (unsigned int), e, E, f, F, g, G
(double), c (char), s (string)
• flags, width, precision, length - modify meaning and number
of characters printed
• Formatted input: scanf() - similar form, takes pointers to
arguments (except strings), ignores whitespace in input

3
Review: Strings and character arrays

• Strings represented in C as an array of characters (char [] )


• String must be null-terminated (’\0’ at end)
• Declaration:
char str [] = "I am a string."; or
char str [20] = "I am a string.";
• strcpy() - function for copying one string to another
• More about strings and string functions today. . .

4
Review

Pointers and Memory Addresses


Physical and Virtual Memory
Addressing and Indirection
Functions with Multiple Outputs

Arrays and Pointer Arithmetic

Strings
String Utility Functions

5
Pointers and addresses

• Pointer: memory address of a variable


• Address can be used to access/modify a variable from
anywhere
• Extremely useful, especially for data structures
• Well known for obfuscating code

5
Physical and virtual memory

• Physical memory: physical resources where data can be


stored and accessed by your computer
• cache
• RAM
• hard disk
• removable storage
• Virtual memory: abstraction by OS, addressable space
accessible by your code

6
Physical memory considerations

• Different sizes and access speeds


• Memory management – major function of OS
• Optimization – to ensure your code makes the best use of
physical memory available
• OS moves around data in physical memory during
execution
• Embedded processors – may be very limited

7
Virtual memory

• Virtual memory maps to different parts of physical memory


• Usable parts of virtual memory: stack and heap
• stack: where declared variables go
• heap: where dynamic memory goes

8
Addressing variables

• Every variable residing in memory has an address!


• What doesn’t have an address?
• register variables
• constants/literals/preprocessor defines
• expressions (unless result is a variable)
• How to find an address of a variable? The & operator
int n = 4;
double p i = 3 . 1 4 1 5 9 ;
i n t ∗pn = &n ; / ∗ address o f i n t e g e r n ∗ /
double ∗ p p i = & p i ; / ∗ address o f double p i ∗ /

• Address of a variable of type t has type t *

9
Dereferencing pointers

• I have a pointer – now what?


• Accessing/modifying addressed variable:
dereferencing/indirection operator *
/ ∗ p r i n t s " p i = 3.14159\n " ∗ /
p r i n t f ( "pi = %g\n" , ∗ p p i ) ;

/ ∗ p i now equals 7.14159 ∗ /


∗ p p i = ∗ p p i + ∗pn ;

• Dereferenced pointer like any other variable


• null pointer, i.e. 0 (NULL): pointer that does not reference
anything

10
Casting pointers

• Can explicitly cast any pointer type to any other pointer


type
ppi = (double ∗)pn; /∗ pn originally of type ( int ∗) ∗/
• Implicit cast to/from void * also possible (more next
week. . . )
• Dereferenced pointer has new type, regardless of real type
of data
• Possible to cause segmentation faults, other
difficult-to-identify errors
• What happens if we dereference ppi now?

11
Functions with multiple outputs

• Consider the Extended Euclidean algorithm


ext_euclid(a,b) function from Wednesday’s lecture
• Returns gcd(a, b), x and y s.t. ax + by = gcd(a, b)
• Used global variables for x and y
• Can use pointers to pass back multiple outputs:
int ext_euclid( int a, int b, int ∗x, int ∗y);
• Calling ext_euclid(), pass pointers to variables to
receive x and y:
int x , y , g;
/ ∗ assume a , b d e c l a r e d p r e v i o u s l y ∗ /
g = e x t _ e u c l i d ( a , b ,& x ,& y ) ;

• Warning about x and y being used before initialized

12
Accessing caller’s variables

• Want to write function to swap two integers


• Need to modify variables in caller to swap them
• Pointers to variables as arguments
void swap ( i n t ∗x , i n t ∗y ) {
i n t temp = ∗x ;
∗x = ∗y ;
∗y = temp ;
}

• Calling swap() function:


int a = 5 , b = 7;
swap(&a , &b ) ;
/ ∗ now , a = 7 , b = 5 ∗ /

13
Variables passing out of scope

• What is wrong with this code?


# include < s t d i o . h>

char ∗ get_message ( ) {
char msg [ ] = "Aren’t pointers fun?" ;
r e t u r n msg ;
}

i n t main ( void ) {
char ∗ s t r i n g = get_message ( ) ;
puts ( s t r i n g ) ;
return 0;
}

14
Variables passing out of scope

• What is wrong with this code?


# include < s t d i o . h>

char ∗ get_message ( ) {
char msg [ ] = "Aren’t pointers fun?" ;
r e t u r n msg ;
}

i n t main ( void ) {
char ∗ s t r i n g = get_message ( ) ;
puts ( s t r i n g ) ;
return 0;
}

• Pointer invalid after variable passes out of scope

14
Review

Pointers and Memory Addresses


Physical and Virtual Memory
Addressing and Indirection
Functions with Multiple Outputs

Arrays and Pointer Arithmetic

Strings
String Utility Functions

15
Arrays and pointers

• Primitive arrays implemented in C using pointer to block of


contiguous memory
• Consider array of 8 ints:
int arr [8];
• Accessing arr using array entry operator:
int a = arr [0];
• arr is like a pointer to element 0 of the array:
int ∗pa = arr ; ⇔ int ∗pa = &arr [0];
• Not modifiable/reassignable like a pointer

15
The sizeof() operator

• For primitive types/variables, size of type in bytes:


int s = sizeof(char); /∗ == 1 ∗/
double f; /∗ sizeof ( f ) == 8 ∗/ (64-bit OS)
• For primitive arrays, size of array in bytes:
int arr [8]; /∗ sizeof ( arr ) == 32 ∗/ (64-bit OS)
long arr [5]; /∗ sizeof ( arr ) == 40 ∗/ (64-bit OS)
• Array length:
/ ∗ needs t o be on one l i n e when implemented ∗ /
# define a r r a y _ l e n g t h ( a r r ) ( s i z e o f ( a r r ) == 0 ?
0 : sizeof ( a r r ) / sizeof ( ( a r r ) [ 0 ] ) )

• More about sizeof() next week. . .

16
Pointer arithmetic

• Suppose int ∗pa = arr ;


• Pointer not an int, but can add or subtract an int from a
pointer:
pa + i points to arr[i]
• Address value increments by i times size of data type
Suppose arr[0] has address 100. Then arr[3] has
address 112.
• Suppose char ∗ pc = (char ∗)pa; What value of i satisfies
( int ∗)(pc+i) == pa + 3?

17
Pointer arithmetic

• Suppose int ∗pa = arr ;


• Pointer not an int, but can add or subtract an int from a
pointer:
pa + i points to arr[i]
• Address value increments by i times size of data type
Suppose arr[0] has address 100. Then arr[3] has
address 112.
• Suppose char ∗ pc = (char ∗)pa; What value of i satisfies
( int ∗)(pc+i) == pa + 3?
• i = 12

17
Review

Pointers and Memory Addresses


Physical and Virtual Memory
Addressing and Indirection
Functions with Multiple Outputs

Arrays and Pointer Arithmetic

Strings
String Utility Functions

18
Strings as arrays

• Strings stored as null-terminated character arrays (last


character == ’\0’)
• Suppose char str [] = "This is a string."; and
char ∗ pc = str ;
• Manipulate string as you would an array
∗(pc+10) = ’S’;
puts( str ); /∗ prints "This is a String ." ∗/

18
String utility functions

• String functions in standard header string.h


• Copy functions: strcpy(), strncpy()
char ∗ strcpy( strto , strfrom ); – copy strfrom to strto
char ∗ strncpy( strto , strfrom ,n); – copy n chars from strfrom
to strto
• Comparison functions: strcmp(), strncmp()
int strcmp(str1, str2 ); – compare str1, str2; return 0 if
equal, positive if str1>str2, negative if str1<str2
int strncmp(str1,str2 ,n); – compare first n chars of str1 and
str2
• String length: strlen()
int strlen ( str ); – get length of str

19
More string utility functions

• Concatenation functions: strcat(), strncat()


char ∗ strcat ( strto , strfrom ); – add strfrom to end of strto
char ∗ strncat ( strto , strfrom ,n); – add n chars from strfrom to
end of strto
• Search functions: strchr(), strrchr()
char ∗ strchr ( str ,c ); – find char c in str, return pointer to
first occurrence, or NULL if not found
char ∗ strrchr ( str ,c ); – find char c in str, return pointer to
last occurrence, or NULL if not found
• Many other utility functions exist. . .

20
Summary

Topics covered:
• Pointers: addresses to memory
• physical and virtual memory
• arrays and strings
• pointer arithmetic

33
Review

User defined datatype


Structures
Unions
Bitfields

1
Review: pointers

• Pointers: memory address of variables


• ’&’ (address of) operator.
• Declaring: int x=10; int ∗ px= &x;
• Dereferencing: ∗px=20;
• Pointer arithmetic:
• sizeof()
• incrementing/decrementing
• absolute value after operation depends on pointer datatype.

1
Review: string.h

• String copy: strcpy(),strncpy()


• Comparison: strcmp(),strncmp()
• Length: strlen()
• Concatenation: strcat()
• Search: strchr(),strstr()

2
Structure

Definition: A structure is a collection of related variables (of


possibly different types) grouped together under a single name.
This is a an example of composition–building complex
structures out of simple ones.
Examples:

s t r u c t employee
struct point {
{ char fname [ 1 0 0 ] ;
int x ; char lname [ 1 0 0 ] ;
int y ; i n t age ;
}; };
/ ∗ n o t i c e t h e ; a t t h e end ∗ / / ∗ members o f d i f f e r e n t
type ∗ /

4
Structure

• struct defines a new datatype.


• The name of the structure is optional.
struct {...} x,y,z;
• The variables declared within a structure are called its
members
• Variables can be declared like any other built in data-type.
struct point ptA;
• Initialization is done by specifying values of every member.
struct point ptA={10,20};
• Assignment operator copies every member of the structure
(be careful with pointers).

5
Structure (cont.)

More examples:

struct t r i a n g l e s t r u c t chain_element
{ {
s t r u c t p o i n t ptA ; i n t data ;
s t r u c t p o i n t ptB ; s t r u c t chain_element ∗ n e x t ;
s t r u c t p o i n t ptC ; };
}; / ∗ members can be
/ ∗ members can be s t r u c t u r e s ∗ / s e l f r e f e r e n t i a l ∗ /

6
Structure (cont.)

• Individual members can be accessed using ’.’ operator.


struct point pt={10,20}; int x=pt.x; int y=pt.y;
• If structure is nested, multiple ’.’ are required
struct rectangle
{
struct p o i n t t l ; / ∗ top l e f t ∗ /
struct p o i n t br ; / ∗ bot r i g h t ∗ /
};
struct rectangle rect ;
i n t t l x = r e c t . t l . x ; / ∗ nested ∗ /
int t l y =rect . t l . y ;

7
Structure pointers
• Structures are copied element wise.
• For large structures it is more efficient to pass pointers.
void foo(struct point ∗ pp); struct point pt ; foo(&pt)
• Members can be accesses from structure pointers using
’->’ operator.
struct point p={10 ,20};
s t r u c t p o i n t ∗ pp=&p ;
pp−>x = 1 0 ; / ∗ changes p . x ∗ /
i n t y= pp−>y ; / ∗ same as y=p . y ∗ /
Other ways to access structure members?
struct point p={10 ,20};
s t r u c t p o i n t ∗ pp=&p ;
( ∗ pp ) . x = 1 0 ; / ∗ changes p . x ∗ /
i n t y= ( ∗ pp ) . y ; / ∗ same as y=p . y ∗ /
why is the () required?
8
Arrays of structures

• Declaring arrays of int: int x [10];


• Declaring arrays of structure: struct point p[10];
• Initializing arrays of int: int x [4]={0,20,10,2};
• Initializing arrays of structure:
struct point p [3]={0,1,10,20,30,12};
struct point p [3]={{0,1},{10,20},{30,12}};

9
Size of structures

• The size of a structure is greater than or equal to the sum


of the sizes of its members.
• Alignment
struct {
char c ;
/ ∗ padding ∗ /
int i ;

• Why is this an important issue? libraries, precompiled files,


SIMD instructions.
• Members can be explicitly aligned using compiler
extensions.
__attribute__ (( aligned(x ))) /∗gcc∗/
__declspec((aligned(x))) /∗MSVC∗/

10
Union

A union is a variable that may hold objects of different


types/sizes in the same memory location. Example:
union data
{
int idata ;
float fdata ;
char ∗ sdata ;
} d1 , d2 , d3 ;
d1 . i d a t a =10;
d1 . f d a t a =3.14F ;
d1 . sdata ="hello world" ;

11
Unions (cont.)

• The size of the union variable is equal to the size of its


largest element.
• Important: The compiler does not test if the data is being
read in the correct format.
union data d; d.idata=10; float f=d.fdata; /∗ will give junk∗/
• A common solution is to maintain a separate variable.
enum dtype { INT , FLOAT,CHAR } ;
struct variant
{
union data d ;
enum dtype t ;
};

12
Bit fields
Definition: A bit-field is a set of adjacent bits within a single
’word’. Example:
struct f l a g {
unsigned i n t i s _ c o l o r : 1 ;
unsigned i n t has_sound : 1 ;
unsigned i n t i s _ n t s c : 1 ;
};

• the number after the colons specifies the width in bits.


• each variables should be declared as unsigned int

Bit fields vs. masks

CLR=0x1,SND=0x2,NTSC=0x4; struct flag f ;


x|= CLR; x|=SND; x|=NTSC f .has_sound=1;f.is_color=1;
x&= ~CLR; x&=~SND; f .has_sound=0;f.is_color=0;
if (x & CLR || x& NTSC) if ( f . is_color || f .has_sound)

13
Digression: dynamic memory allocation
void∗ malloc(size_t n)
• malloc() allocates blocks of memory
• returns a pointer to unitialized block of memory on
success
• returns NULL on failure.
• the returned value should be cast to appropriate type using
(). int∗ ip=(int∗)malloc(sizeof(int)∗100)
void∗ calloc( size_t n,size_t size)
• allocates an array of n elements each of which is ’size’
bytes.
• initializes memory to 0
void free(void∗)
• Frees memory allocated my malloc()
• Common error: accessing memory after calling free
14
Review

More about Pointers


Pointers to Pointers
Pointer Arrays
Multidimensional Arrays

1
Review: Compound data types

• struct - structure containing one or multiple fields, each with


its own type (or compound type)
• size is combined size of all the fields, padded for byte
alignment
• anonymous or named
• union - structure containing one of several fields, each with
its own type (or compound type)
• size is size of largest field
• anonymous or named
• Bit fields - structure fields with width in bits
• aligned and ordered in architecture-dependent manner
• can result in inefficient code

1
Review: Compound data types

• Consider this compound data structure:

struct foo {
short s ;
union {
int i ;
char c ;
} u;
unsigned i n t f l a g _ s : 1 ;
unsigned i n t f l a g _ u : 2 ;
unsigned i n t bar ;
};

• Assuming a 32-bit x86 processor, evaluate


sizeof(struct foo)

2
Review: Compound data types

• Consider this compound data structure:

struct foo {
short s ; ← 2 bytes
union { ← 4 bytes,
int i ; 4 byte-aligned
char c ;
} u;
unsigned i n t f l a g _ s : 1 ; ← bit fields
unsigned i n t f l a g _ u : 2 ;
unsigned i n t bar ; ← 4 bytes,
}; 4 byte-aligned

• Assuming a 32-bit x86 processor, evaluate


sizeof(struct foo)

2
Pointer review

• Pointer represents address to variable in memory


• Examples:
int ∗pn; – pointer to int
struct div_t ∗ pdiv; – pointer to structure div_t
• Addressing and indirection:
double p i = 3 . 1 4 1 5 9 ;
double ∗ p p i = & p i ;
p r i n t f ( "pi = %g\n" , ∗ p p i ) ;

• Today: pointers to pointers, arrays of pointers,


multidimensional arrays

5
Pointers to pointers

• Address stored by pointer also data in memory


• Can address location of address in memory – pointer to
that pointer
int n = 3;
i n t ∗pn = &n ; / ∗ p o i n t e r t o n ∗ /
i n t ∗∗ppn = &pn ; / ∗ p o i n t e r t o address o f n ∗ /

• Many uses in C: pointer arrays, string arrays

6
Pointer pointers example

• What does this function do?


void swap ( i n t ∗∗a , i n t ∗∗b ) {
i n t ∗temp = ∗a ;
∗a = ∗b ;
∗b = temp ;
}

7
Pointer pointers example

• What does this function do?


void swap ( i n t ∗∗a , i n t ∗∗b ) {
i n t ∗temp = ∗a ;
∗a = ∗b ;
∗b = temp ;
}

• How does it compare to the familiar version of swap?


void swap ( i n t ∗a , i n t ∗b ) {
i n t temp = ∗a ;
∗a = ∗b ;
∗b = temp ;
}

7
Pointer arrays

• Pointer array – array of pointers


int ∗arr [20]; – an array of pointers to int’s
char ∗arr [10]; – an array of pointers to char’s
• Pointers in array can point to arrays themselves
char ∗strs [10]; – an array of char arrays (or strings)

8
Pointer array example

• Have an array int arr [100]; that contains some numbers


• Want to have a sorted version of the array, but not modify
arr
• Can declare a pointer array int ∗ sorted_array[100]; containing
pointers to elements of arr and sort the pointers instead
of the numbers themselves
• Good approach for sorting arrays whose elements are very
large (like strings)

9
Pointer array example

Insertion sort:
/ ∗ move p r e v i o u s elements down u n t i l
i n s e r t i o n p o i n t reached ∗ /
void s h i f t _ e l e m e n t ( unsigned i n t i ) {
i n t ∗ pvalue ;
/ ∗ guard a g a i n s t going o u t s i d e a r r a y ∗ /
f o r ( pvalue = s o r t e d _ a r r a y [ i ] ; i &&
∗ s o r t e d _ a r r a y [ i −1] > ∗ pvalue ; i −−) {
/ ∗ move p o i n t e r down ∗ /
s o r t e d _ a r r a y [ i ] = s o r t e d _ a r r a y [ i −1];
}
s o r t e d _ a r r a y [ i ] = pvalue ; / ∗ i n s e r t p o i n t e r ∗ /
}

10
Pointer array example

Insertion sort (continued):


/ ∗ i t e r a t e u n t i l out−of−o r d e r element found ;
s h i f t t h e element , and c o n t i n u e i t e r a t i n g ∗ /
void i n s e r t i o n _ s o r t ( void ) {
unsigned i n t i , l e n = a r r a y _ l e n g t h ( a r r ) ;
f o r ( i = 1 ; i < l e n ; i ++)
i f ( ∗ s o r t e d _ a r r a y [ i ] < ∗ s o r t e d _ a r r a y [ i −1])
shift_element ( i ) ;
}

11
String arrays

• An array of strings, each stored as a pointer to an array of


chars
• Each string may be of different length
char s t r 1 [ ] = "hello" ; / ∗ l e n g t h = 6 ∗ /
char s t r 2 [ ] = "goodbye" ; / ∗ l e n g t h = 8 ∗ /
char s t r 3 [ ] = "ciao" ; / ∗ l e n g t h = 5 ∗ /
char ∗ strArray [ ] = { str1 , str2 , str3 } ;

• Note that strArray contains only pointers, not the characters


themselves!

12
Multidimensional arrays

• C also permits multidimensional arrays specified using [ ]


brackets notation:
int world [20][30]; is a 20x30 2-D array of int’s
• Higher dimensions possible:
char bigcharmatrix [15][7][35][4]; – what are the dimensions of
this?
• Multidimensional arrays are rectangular; pointer arrays can
be arbitrary shaped

13
Summary

Topics covered:
• Pointers to pointers
• pointer and string arrays
• multidimensional arrays

37

You might also like