struct complex
{
double real;
double imag;
};
|
struct complex c2, c3; |
complex c1; /* WRONG */ |
struct complex {
double real;
double imag;
} c1, c2, c3;
|
struct {
double real;
double imag;
} c1, c2, c3;
|
struct complex; |
c1.real = 1; c1.imag = c2.imag; c1.real = c2.real + c3.real; |
c1 = c2; |
struct complex c1 = {1, 2};
struct complex c2 = {3, 4};
|
/* add two two complex numbers */
struct complex cpx_add(struct complex c1, struct complex c2)
{
struct complex sum;
sum.real = c1.real + c2.real;
sum.imag = c1.imag + c2.imag;
return sum;
}
|
c1 = cpx_add(c2, c3) |
c1 = c2 + c2; /* NOT in C! */ |
struct complex *p1, *p2; |
p1 = &c2; p2 = &c3; *p1 = *p2; /* copy c3 to c2 */ p1 = p2; /* copy p1 to p2 */ |
(*p1).real |
p->real |
struct listnode
{
char *item;
struct listnode *next;
};
|
struct listnode node2 = {"world", NULL};
struct listnode node1 = {"hello", &node2};
struct listnode *head = &node1;
|
struct listnode *lp;
for (lp = head; lp != NULL; lp = lp->next)
printf("%s\n", lp->item);
|
| initialize | lp = head |
| test | lp != NULL |
| increment pattern | lp = lp->next |
#include |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct listnode *prepend(char *newword, struct listnode *oldhead)
{
struct listnode *newnode = malloc(sizeof(struct listnode));
if (newnode == NULL) {
fprintf(stderr, "out of memory\n");
exit(1);
}
newnode->item = malloc(strlen(newword) + 1);
if (newnode->item == NULL) {
fprintf(stderr, "out of memory\n");
exit(1);
}
strcpy(newnode->item, newword);
newnode->next = oldhead;
return newnode;
}
|
struct listnode *newnode;
if ((newnode = malloc(sizeof(struct listnode))) == NULL ||
(newnode->item = malloc(strlen(newword) + 1)) == NULL)
{
fprintf(stderr, "out of memory\n");
exit(1);
}
|
struct listnode *newnode;
if ((newnode = malloc(sizeof(struct listnode))) == NULL ||
(newnode->item = malloc(strlen(newword) + 1)) == NULL)
{
fprintf(stderr, "out of memory\n");
exit(1);
}
|
#define MAXLINE 200
char line[MAXLINE];
struct listnode *head = NULL;
struct listnode *lp;
while(getline(line, MAXLINE) != EOF)
head = prepend(line, head);
for(lp = head; lp != NULL; lp = lp->next)
printf("%s\n", lp->item);
|