CS 330 Lecture 23 – Cisms Cont’d
Agenda
- what ?s
- enums and type safety
- the C preprocessor
- macro danger
- dynamic memory allocation
- memory allocation
When do I dynamically allocate memory?
- When you don’t know how much memory you’ll need at compile time. You don’t know if the size depends on a function parameter.
- When you allocate memory within a function but need the memory to outlive the function.
Otherwise, use the stack.
When do I need pointers?
- When you need cheap sharing of data from caller to callee.
- When you need a function to return multiple values (out parameters).
- When you dynamically allocate.
Code
blackjack.c
#include <stdio.h>
#include <stdlib.h>
enum suit_t {
DIAMONDS,
HEARTS,
CLUBS,
SPADES
};
enum rank_t {
ACE = 1,
DEUCE,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK = 10,
QUEEN = 10,
KING = 10
};
struct card_t {
enum suit_t suit;
enum rank_t rank;
};
int score(struct card_t *hand, int ncards) {
int sum = 0;
int naces = 0;
for (int i = 0; i < ncards; ++i) {
if (hand[i].rank == ACE) {
++naces;
} else {
sum += hand[i].rank;
}
}
if (naces > 0) {
if (sum + 11 + naces - 1 <= 21) {
sum += 11 + naces - 1;
} else {
sum += naces;
}
}
return sum;
}
int main(int argc, char **argv) {
struct card_t hand[] = {
{CLUBS, JACK},
{SPADES, ACE},
{101, -5}
};
printf("score(hand): %d\n", score(hand, 3));
return 0;
}
include.c
#include "limits.h"
int main(int argc, char **argv) {
return 0;
}
c2i.c
#include <stdio.h>
#include <stdlib.h>
/* #define C2I(c, r, width) c + r * width */
#define C2I(c, r, width) (c) + (r) * (width)
int main(int argc, char **argv) {
printf("C2I(3, 1, 4): %d\n", C2I(3, 1, 4));
printf("C2I(3, 1, 4): %d\n", C2I(3, 1 + 1, 4));
return 0;
}
BlackJack21.java
public class BlackJack21 {
public static void main(String[] args) {
new Card(Suit.SPADES, Rank.NINE);
// new Card(101, -5);
}
}
class Card {
private Suit suit;
private Rank rank;
public Card(Suit suit, Rank rank) {
this.suit = suit;
this.rank = rank;
}
}
enum Suit {
HEARTS,
DIAMONDS,
CLUBS,
SPADES
}
interface Foo {
enum Force {
GOOD,
EVIL,
};
}
enum Rank {
ACE(1),
DEUCE(2),
THREE(3),
FOUR(4),
FIVE(5),
SIX(6),
SEVEN(7),
EIGHT(8),
NINE(9),
TEN(10),
JACK(10),
QUEEN(10),
KING(10);
private int value;
private Rank(int value) {
this.value = value;
}
}
Haiku
Karma uses void stars
Anything dead can go in
Out comes something else
Anything dead can go in
Out comes something else