9/10/02 Tue
#define ARRAY_SIZE 10 double array1[ARRAY_SIZE];
double average(int a[], int n)
{
double result = 0.0;
for (i = 0; i < n; i++) {
result += array1[i];
}
return (result / n);
}
int main(void)
{
double array2[10];
double *array3;
fill_array(array1);
fill_array(array2);
array3 = (double *) malloc(sizeof(double) * ARRAY_SIZE);
fill_array(array3);
printf("Average of array 1, 2 and 3 are: %lf, %lf, %lf\n",
average(array1), average(array2), average(array3));
free(array3);
return 0;
}
Allocation memory dynamically:
ptr = (type *) malloc (sizeof(type) * ARRAY_LENGTH);
The memory can be deallocated:
free (ptr);
char* strdup(char *str)
{
char *result;
_____________________
strcpy(result, str); return result; }
struct point {
int x;
int y;
};
struct point pt;
pt.x = 0; pt.y = 10;
double sqrt(double x);
struct point {
double x;
double y;
};
double dist(struct point pt1, struct point pt2)
{
return sqrt(____________________);
}
struct point *p1;
struct point pt1; struct point *p1 = &pt1;
struct point pt1, pt2; struct point *p1 = &pt1; (*p1).x = 0; (*p1).y = 1; pt2 = *p1;
|
(*p1).x = 0; |
is equivalent to |
p1->x = 0; |
double dist(struct point *p1, struct point *p2)
{
return sqrt(_________________________________);
}
struct point {
double x;
double y;
};
typedef struct point point;
|
is equivalent to |
typedef struct point {
double x;
double y;
} point;
|
typedef struct point * ppoint;
struct lnode {
char *word;
struct lnode *next;
};
typedef struct lnode lnode; typedef struct lnode * plnode;
plnode addhead(plnode head, char *str)
{
plnode *temp;
if (head == NULL) {
temp = (plnode)malloc(sizeof(lnode));
temp->word = strdup(str);
temp->next = NULL;
return temp;
}
else {
temp = (plnode)malloc(sizeof(lnode));
temp->word = strdup(str);
temp->next = head;
return temp;
}
}
void print_list(plnode head)
{
plnode *temp;
for (temp = head; temp != NULL; temp = temp->next) {
printf("%s\n", temp->word);
}
}
void delete_list(plnode head)
{
plnode *old, *temp = head;
while (temp != NULL) {
old = temp;
temp = temp->next;
free (old->word);
}
}
int main(void)
{
char *test_string[] = {
"This", "is", "a", "test." };
int n = sizeof(test_string) / sizeof(test_string[0]);
plnode *head;
for (i = 0; i < n; i++) {
head = addhead(head, test_string[i]);
}
print_list(head);
delete_list(head);
return 0; }
plnode addtail(plnode head, char *str)
{
plnode *p, *temp;
if (head == NULL) {
temp = (plnode)malloc(sizeof(lnode));
temp->word = strdup(str);
temp->next = NULL;
return temp;
}
else {
for (p = head; p->next != NULL; p = p->next)
;
temp = (plnode)malloc(sizeof(lnode));
temp->word = strdup(str);
___________________
___________________
return head; } }