CS 330 Lecture 13 – Strings and structs
Agenda
- array out-of-bounds
- strings null-terminated char arrays
- strlen
- strcat
- strcpy
- strdup
- strcmp
- structs
- header files
- a stack API
- evaluating postfix expressions
- for each token
- if token is number, push it on operand stack
- if token is operator, pop two operands, push result back on
- pop stack to get the value
Code
makefile
EXES = first arrays months oob strings all: $(EXES) $(EXES): %: %.c gcc -o $@ -Wall -std=c99 $< clean: rm -f $(EXES)
oob.c
#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { double nums[100]; for (int i = 0; i < 5; ++i) { nums[i] = rand() / (float) RAND_MAX; } return 0; }
strings.c
#include <stdio.h> #include <stdlib.h> /* ------------------------------------------------------------------------- */ /* int strlen(const char *s) { */ /* for (int i = 0; i < */ /* int i = 0; */ /* while (s[i] != '\0') { */ /* i++; */ /* } */ /* return i; */ /* } */ /* ------------------------------------------------------------------------- */ int strlen(const char *s) { const char *ps = s; int i = 0; while (*ps != '\0') { i++; ps++; } return i; } /* ------------------------------------------------------------------------- */ int main(int argc, char **argv) { char name[] = "Jeff"; /* name[0] = 'J'; */ /* name[1] = 'e'; */ /* name[2] = 'f'; */ /* name[3] = 'f'; */ /* name[4] = '\0'; // name[4] = 0; */ /* name[4] = 'a'; // name[4] = 0; */ printf("name: %s\n", name); printf("strlen(name): %d\n", strlen(name)); return 0; }
stack.h
#ifndef STACK_H #define STACK_H struct stack_t { int elements[100]; int top; } struct stack_t *make_stack(); // Add element to stack void push(int new_thing); int pop(); int peek(); #endif
stack.cpp
#include "stack.h" struct stack_t *make_stack() { struct stack_t *new_stack = malloc(sizeof(struct stack_t)); new_stack->elements = ; new_stack->top = 0; }
Haiku
Java is flying.
C is tunneling. Through rock.
I fly through tunnels.
C is tunneling. Through rock.
I fly through tunnels.