Pointers and Structures in C

Where all the fun starts

18 February 2020

Obed N Munoz

Cloud Software Engineer

Pointer

A pointer is a variable that contains the address of a variable.

int x = 1, y = 2, z[10];

int *ip;         /* ip is a pointer to int */

ip = &x;         /* ip now points to x */

y = *ip;         /* y is now 1 */

*ip = 0;         /* x is now 0 */

ip = &z[0];      /* ip now points to z[0] */
2

Pointers in Functions 1/2

void swap(int x, int y)
{
   int temp;
   temp = x;
   x = y;
   y = temp;
}
void swap(int *px, int *py)
{
    int temp;
    temp = *px;
    *px = *py;
    *py = temp;
}

So, what would be used in the main function?

3

Pointers in Functions 2/2

4

Pointers and Arrays 1/2

int a[10]; // Defines an array of 10 elements
int *pa;
pa = &a[0];
5

Pointers and Arrays 2/2

How to access a's elements from *pa

Then,

*pa == a[0]
*(pa + 1) == a[1]
*(pa + 2) == a[2]
*(pa + n) == a[n]
6

Multi-dimensional arrays

static char daytab[2][13] = {
    {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
/* Get year day from a given year,month and day combination */
int day_of_year(int year, int month, int day)
{
    int i, leap;
    leap = year%4 == 0 && year%100 != 0 ¦¦ year%400 == 0;

    for (i = 1; i < month; i++)
        day += daytab[leap][i];
    return day;
}
7

Let's code: month day calculator

From previous example,

/* month_day function's prototype*/
void month_day(int year, int yearday, int *pmonth, int *pday)

classify.obedmr.com/get-lab/ap-labs/month-day

8

Pointer Arrays

/* month_name:  return name of n-th month */
char *month_name(int n) {

   static char *name[] = {
       "Illegal month",
       "January", "February", "March",
       "April", "May", "June",
       "July", "August", "September",
       "October", "November", "December"
   };

   return (n < 1 ¦¦ n > 12) ? name[0] : name[n];
}
9

Pointer vs. Multi-dimensional arrays 1/2

int a[10][20];
int *b[10];

What's the difference between a and b?

10

Pointer vs. Multi-dimensional arrays 2/2

char *name[] = { "Illegal month", "Jan, "Feb", "Mar" };
char aname[][15] = { "Illegal month", "Jan", "Feb", "Mar" };
11

Pointers to functions

12

Let's code: Generic Merge Sort

classify.obedmr.com/get-lab/ap-labs/generic-merge-sort

13

Structures ...

Read the Chapter 6 - Structures in the The C Programming Language book.

14

Resources and Credits

This material is genereated thanks to some extracts from following resources:

15

Thank you

Obed N Munoz

Cloud Software Engineer

Use the left and right arrow keys or click the left and right edges of the page to navigate between slides.
(Press 'H' or navigate to hide this message.)