C Lecture 2
[Previous Lecture]
[Lecture Index]
[Next Lecture]
Functions
return-type
function-name ( arg-1-type arg-1-name ,
arg-2-type arg-2-name , etc )
{
function-body
}
Examples:
int
strlen(char *str)
{
int len;
for (len = 0; str[len]; len++)
;
return len;
}
double
poweri(double val, int power)
{
int sign = 1;
int i;
double result = 1.0;
if (power < 0) {
sign = -1;
power = -power;
}
for (i = 0; i < power; i++)
result *= val;
if (sign < 0)
result = 1 / result;
return result;
}
fgets.c
#include <stdio.h>
char *
fgets(char *buf, int bsize, FILE *fp)
{
int i;
int c;
int done = 0;
if (buf == 0 || bsize <= 0 || fp == 0)
return 0;
for (i = 0; !done && i < bsize - 1; i++) {
c = fgetc(fp);
if (c == EOF) {
done = 1;
i--;
} else {
buf[i] = c;
if (c == '\n')
done = 1;
}
}
buf[i] = '\0';
if (i == 0)
return 0;
else
return buf;
}
Memory Layout (simplified)
Memory is divided into three `areas' or `sections':
- instruction (aka text)
- contains program itself (instructions for the CPU)
- typically read only
- data
- contains global variables
- read/write
- stack
- contains function parameters, local variables
and `function call stack'
- read/write
[Previous Lecture]
[Lecture Index]
[Next Lecture]