Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

SEMICON Solutions

Advanced C programming

15/07/2016
Agenda

 Pointers
 Arrays
 User-Defined Types
 Memory Allocations
 Linked List
Pointers
Limitations of Reference by value
Write a C function that does the following
Argument: the radius of a circle r
Output: circumference c and area a
#include <stdio.h> Reference by value
#define PI 3.14 does not allow the
void circle(float r, float a, float c);
manipulation of
int main(void) variables external
{ to the function!!!
float r, a=0, c=0;
printf("Enter the radius of the circle:");
scanf("%f",&r);
circle(r, a, c); // arguments passed by value
printf("Area:%.1f Circumference:%.1f\n", a, c);
return(0);
}

void circle(float r, float a, float c)


{ a = PI*r*r; // computation of area
c = 2*PI*r; // computation of circumference
}
The concept of Pointers
 Pointer: A variable containing the address of another variable
A label used to refer (point) to memory space

Page numbers in a book, or PowerPoint slides


Page numbers are pointers point to the contents of the particular page

3
The concept of Pointers
 Mail boxes at the post office

 Numbers are used to label


each mailbox

 The contents (letters) of a


particular mailbox can be
retrieved by referring to the
mail box number.
Pointers in C
Labels for referencing memory addresses

1 45

2 678

Address 3 3.36 Contents

4 ‘a’

5 112

6 5.83
Why do we need pointers

 Faster memory access and usage via memory


referencing
Required for programming resource-constrained devices such as
microcontrollers
 Saving memory space
No need to hold local copies of variables inside function
Can pass values to a function by reference
 Downside
Pointers usually make program tracking/reading more complicated
Declaration of pointers
 Basic syntax
Syntax: data type *name;

Examples: FILE *inp; // pointer to a file


int *p; // pointer to an integer variable
float *p; // pointer to a float variable

P var
Changing the Address of a Pointer

 Use the address operator &


 The type of pointer and type of the variable must match

Syntax: pointer = &var;

Examples: int *p; // pointer to an integer


int i; // an integer variable
p = &i; // p points to variable i
Changing the contents of the memory

 We use contents operator *

Syntax: *pointer = value;


variable = *pointer;

Examples: int *p; // pointer to an integer


*p = 10; // memory cell pointed by p is
assigned the value 10
var1 = *p; // variable var1 is assigned the
contents of memory cell
pointed by p
A Simple Example Using Pointers

#include<stdio.h>

int main(void)
{

int var1, var2;


int *p; // declaration of a pointer of type integer
p= &var1; // initialization of pointer to address of var1
*p=10; // initialization of var1 via pointer p
var2 = *p+10; // var2 = var1 + 10

printf("%d %d %d\n", var1, var2, *p);


printf("%p %p %p\n", p, &var1, &var2); // printing addresses
return (0);
}
Multiple Pointers on the Same Address
 Three pointers p1, p2, p3, one variable c
#include <stdio.h>

int main(void)
{
char *p1, *p2, *p3; // three pointers of type char
char c; // a char variable
p1=&c; // p1 now points to c
*p1='a'; // value of c changed to 'a'
p2=p1; // p2 is assigned the arithmetic value of p1
p3=p2; // p3 is assigned the arithmetic value of p2

printf("%c %c %c\n",*p1, *p2, *p3);


printf("%p %p %p\n", p1, p2, p3);
printf(”%p %p %p\n", &p1, &p2, &p3);
return(0);
}
Multiple Pointers on the Same Address

 All three pointers point to the same variable

p1

p2 c

a
p3
Re-visiting the circle function
#include<stdio.h>
#define PI 3.14
void circle(float r, float *p_a, float *p_c);

int main(void)
{
float r, a=0, c=0;
printf("Enter the radius of the circle:");
scanf("%f",&r);
circle(r, &a, &c); // arguments passed by value
printf("Area:%.1f Circumference:%.1f\n", a, c);
return(0);
}

void circle(float r, float *p_a, float *p_c)


{ *p_a = PI*r*r; // computation of area
*p_c = 2*PI*r; // computation of circumference
}
Arrays
Motivation for Array data Types
 Write a programs that counts the frequency of occurrence of various
letters in a text file

 Input: Text file

 Output: fa, fb … fz
 Algorithm:
 Scan the file letter by letter
 Increase counter corresponding to a letter by one, every time this letter is read
 Divide by the total number of characters to find the frequency
Arrays
 A collection of two or more adjacent memory cells, called
array elements associated with a single symbolic name

First memory cell 2 x[0]


5 x[1]
6 x[2]
1 x[3]
7 x[4]
9 x[5]
8 x[6]
2 x[7]
Basics of arrays
 Allows identical variables to be grouped into a composite data structure
 Declaring and referencing arrays
Declaration specifies array name and the number of elements in the array

Syntax: array type name[# of elements];


Examples: int counters[26];
double temp[10];
char initial[20];

 The number of elements must be a defined (may use constants


through #define )
The elements are numbered from 0, 1, 2, ..., n-1
Every element of the array may be viewed as an independent variable
C does not check for array boundaries; so be careful in accessing arrays
Array Initialization

 You can declare more than one array on a single type


declaration

Example:
int scores[30], x, pins[10];
double temp[10], limit;
char initial[20];

 Initialization – Can be done at declaration


Example:
int scores[]={0, 0, 0, 0, 0};
char vowels[]={‘a’, ‘e’, ‘i‘, ‘o’, ‘u’, ‘y’}
Using loops to sequentially access arrays

 Arrays can be sequentially accessed using a for loop.


Example:
float scores[]={10.5, 30.2, 20.23, 50.6, 90 100};
int i;

for (i=0; i<6; i++)


printf{“%d\t%f”, i, scores[i]);

Can also be used for array initialization

#define SIZE 100

int scores[SIZE], i;

for (i=0; i<SIZE; i++)


scores[i]=0;
Back to our Initial Problem
 Write a programs that counts the frequency of occurrence of
various letters in a text file

 Algorithm:
 Scan the file letter by letter
 Increase counter corresponding to a letter by one, every time this letter is
read

a b c d e f g h i j k l m n o p q r s t u v w x y z
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
User-Defined Types
Dealing with Multiple-type Objects
 Built-in C data types are limited to: integers, characters,
floating point numbers
 Problem: Programmers have to deal with real-word objects
 Each object has multiple attributes that must be stored and
manipulated
User-Defined Types

 Define new data types called structures that are


aggregates of fundamental data types (or other
defined structures)
 Allow us to efficiently handle real-world objects
typedef struct {
char name[20]; // name of the planet
double diameter; // diameter of the planet in km
int moons; // number of moon
double orbit_time; // orbit around the sun in years
double rotation_time; // orbit around itself in years
} planet_t;
Structure Type Definition
Syntax:
typedef struct {
type_1 var;
type_2 var;
. . .
type_n var;
} struct_name;

Example: typedef struct { // complex number structure


double real_part,
imag_part;
} complex_t;
Hierarchy of Structures

 A user defined structure containing other


structures

typedef struct {
char solar[20]; // name of the solar system
double diameter; // diameter of the solar system in km
planet_t planets[9]; // array of planets
} solar_system;
Manipulating Individual components of structures
Accessing Components within the Hierarchy

typedef struct {
char solar[20]; // name of the solar system
double diameter; // diameter of the solar system in km
planet_t planets[9]; // array of planets
} solar_system;

solar_system solar1;

printf("The diameter of the first planet of solar system %s is %.1f", solar1.solar,


solar1.planets[0].diameter);
Implementation of Scanning
void scan_planet(planet_t *plnp)
{
printf("Enter the name of the planet:");
scanf("%s", (*plnp).name);
printf("Enter the diameter of the planet in Km:");
scanf("%lf", &(*plnp).diameter);
printf("Enter the number of moons:");
scanf("%d", &(*plnp).moons);
printf("Enter the orbit time in years:");
scanf("%lf", &(*plnp).orbit_time);
printf("Enter the rotation time in years:");
scanf("%lf", &(*plnp).rotation_time);
}

In the main: planet_t planet1;


scan_planet(&planet1);
Snapshot at the memory
The Indirect Component Selection Operator
 Replacing the (*pointer) operator
void scan_planet(planet_t *plnp)
{
printf("Enter the name of the planet:");
scanf("%s", plnp->name);
printf("Enter the diameter of the planet in Km:");
scanf("%lf", &plnp->diameter);
printf("Enter the number of moons:");
scanf("%d", &plnp->moons);
printf("Enter the orbit time in years:");
scanf("%lf", &plnp->orbit_time);
printf("Enter the rotation time in years:");
scanf("%lf", &plnp->rotation_time);
}

 In the main:
planet_t planet1;
scan_planet(&planet1);
Dynamic Memory Allocation
 Function of the stdlib.h library for dynamic allocation

Syntax: pointer_var = (data type *)malloc(byte number)

pointer to memory cast to datatype number of bytes reserved


 Examples

int *nump;
char *letp; STEP 1
planet_t *planetp;

nump = (int *)malloc(4); STEP 2


letp = (char *)malloc(sizeof(char));
planetp = (planet_t *)malloc(sizeof(planet_t);
After Memory has been Aallocated

 Memory is reserved in
memory area called
heap
Referencing to the newly allocated memory
 Same way that we would access contents using pointers

*nump = 307;
*letp = ‘Q’;
Example for the use of malloc
#include<stdio.h>
// library for allocating memory
#include<stdlib.h>

int main(void)
{
int *temp; //pointer to an int
int x, y;

// allocating memory for one integer


temp=(int *)malloc(sizeof (int));
printf("Give me an integer:");
scanf("%d",temp); // no & sign, temp is a pointer

x=(*temp)*10;
y=(*temp)*2;
free(temp); // freeing memory allocated to temp
printf("%d, %d\n", x,y);
return (0);
}
Dynamic Allocation of Memory for a Structure
typedef struct {
char name[20]; // name of the planet
double diameter; // diameter of the planet in km
int moons; // number of moon
double orbit_time; // orbit around the sun in years
double rotation_time; // orbit around itself in years
} planet_t;

int main(void)
{
planet_t *pl3; // pointer to a planet

//allocation of memory to store one planet


pl3=(planet_t *)malloc(sizeof(planet_t));

scan_planet(pl3); // initialization of planet


print_planet(*pl3); // printing the planet
return(0);
}
Linked List
Need for Truly Dynamic “Arrays”
Assume the following structure
typedef struct node_s {
char name[20];
int age;
struct node_s *listp;
} node_t;
Consecutive executions of malloc reserve different parts of the memory

name age name age

name age

Goal is to connect the different pieces of memory


ECE 175
Structures with Pointer attributes

 Declaration of structures with pointer attributes to


themselves
typedef struct node_s {
char name[20];
int age;
struct node_s *listp;
} node_t;

name age listp


Creation of a Linked List

 To create a linked list we need to


 Create a head pointer that points to the first element, so we can
traverse the list from the start
 Create a head pointer that points to the first element, so we can
traverse the list from the start
 Create a head pointer that points to the first element, so we can
traverse the list from the start
Creation of a Linked List
int main(void)
{
int i=0;
node_t *headp, *temp, *current=NULL, *lastp;
FILE *inp;
char c;
char s1[20];

inp=fopen("database.dat", "r");

while(!feof(inp))
{
temp=(node_t *)malloc(sizeof (node_t)); // creation of memory
scan_fun(temp, inp); // initialization of element of list
if (current==NULL)
headp=temp; // setting the head of the list
else
current->listp=temp; // else connecting to previous element
i++; // count number of elements added
current=temp; // updating the current element
temp->listp=NULL; // setting pointer to null.
}
Traversing the List
Adding a new Element at the End of the List
Searching the List by Name

 Searching by the name attribute

node_t *find_name(node_t *pt, char *query)


{ // finds the name query in the database
// returns pointer to structure matched or null
while(strcmp(pt->name, query)!=0 && pt!=NULL)
{
pt=pt->listp;
}
return pt;
}
Deleting a member
Deleting a member
void delete_member(node_t **h, node_t **c)
{
node_t *target; // pointer to string to be deleted
node_t **temp=h; // pointer to the head of the list
char s[20];

printf("Enter the name of the entry you want to delete:");


fflush(stdin);
scanf("%s",s);
target=find_name(*h, s); // finding the element to be deleted
if (target==NULL)
printf("This entry does not exist\n");
else
{
while ((*temp)!=target)
{
temp=&(*temp)->listp; // locating the address of the previous element
}
if (target==*h) // if first element must be deleted
*h=target->listp; // make head point to the next element
if (target==*c) // if last element is to be deleted
*c=*temp; // update the position of the last element
*temp=target->listp; // skip element to be deleted
free(target); // free the memory
}
}
Q&A

You might also like