Tom Kelliher, CS 320
Jan. 28, 2005
Read 1.5--9.
I/O in C.
Memory allocation in C.
Complete the exercise from last time. You did sketch out the code, didn't you?
struct <struct_identifier> { <member_declaration> [<member_declaration> ...] }; /* Don't forget the semicolon!!! */
#include <stdio.h> /* "struct dimension" becomes a new type. */ struct dimension { double length; double width; double height; }; /* Prototypes */ void printDimension(struct dimension); int main() { struct dimension box1 = { 1.0, 1.0, 1.0 }; struct dimension box2; box2.length = 2.0; box2.width = 4.0; box2.height = 6.0; printDimension(box2); return 0; } void printDimension(struct dimension dim) { printf("Length: %g\nWidth: %g\nHeight: %g\n", dim.length, dim.width, dim.height); }
double data[10]; double *p_data; int sum; int *p_sum; p_data = data; p_data[3] = 0.0; p_sum = ∑ sum = 10; printf("Sum: %d\n", p_sum); *p_sum = 12; /* Dereference the pointer */;
double sum; double data[10]; double *dp; int i; sum = 0.0; for (i = 0, dp = data; i < 10; i++, dp++) sum += *dp;Note that
dp
will be incremented by sizeof(double)
.
data[4]
is another way of writing *(data + 4)
.
int strlen(char *s) { char *ptr = s; while (*ptr != '\0') ptr++; return ptr - s; }