C Programming: Homework 5
C Programming: Homework 5
C Programming: Homework 5
Homework 5
Pointers
Variables that store memory addresses
Declaration
<variable_type> *<name>;
int *ptr;
int var = 77;
ptr = &var;
Dereferencing Pointers
Accessing the value that the pointer points to
Example:
double x, *ptr;
ptr = &x;
*ptr = 7.8;
Pointer Example
int *x;
int *y;
int var; x = &var;
*x = 42;
Pointer Example
*y = 13;
y = x;
*x = 13;
*y = 13;
or
Pointers to Pointers
char c = A
*cPtr = &c
**cPtrPtr = &cPtr
Pointers to Functions
Also known as: function pointers or functors
Goal: write a sorting function
Has to work for ascending and descending sorting
order + other
How?
Write multiple functions
Provide a flag as an argument to the function
Polymorphism and virtual functions
Use function pointers!!
Pointers to Functions
User can pass in a function to the sort
function
Declaration
double (*func_ptr) (double, double);
Structs
No classes in C
Used to package related data (variables of different
types) together
Single name is convenient
struct Student {
char name[64];
char UID[10];
int age;
int year;
};
struct Student s;
typedef struct {
char name[64];
char UID[10];
int age;
int year;
} Student;
Student s;
Dynamic Memory
Memory that is allocated at runtime
Allocated on the heap
void *malloc (size_t size);
Allocates size bytes and returns a pointer to the allocated
memory
Reading/Writing Characters
int getchar();
Returns the next character from
stdin
Formatted I/O
int fprintf(FILE * fp, const char * format, );
int fscanf(FILE * fp, const char * format, );
FILE *fp can be either:
A file pointer
stdin, stdout, or stderr
Compiling a C program
gcc o FooBarBinary -g foobar.c
gcc is the name of the compiler
The o option indicates the name of the
binary/program to be generated
The g option includes symbol and sourceline info for debugging
foobar.c is the source code to be compiled
Homework 5
Write a C program called srot13
Reads stdin byte-by-byte (getchar)
Consists of records that are newline-delimited
Error checking
Dynamic memory allocation
Example
qsort Example
#include <stdio.h>
#include <stdlib.h>
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main ()
{
int values[] = { 40, 10, 100, 90, 20, 25 };
qsort (values, 6, sizeof(int), compare);
int n;
for (n = 0; n < 6; n++)
printf ("%d ",values[n]);
return 0;
}
Homework Hints