1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* This structure is somewhat similar to the maze used in the homework.
*
* This version adds a function to print the party, as well as fields for
* num_daze_cols and num_daze_rows, as needed for that function.
*/
typedef struct _Party { // ON OUR PLATFORM
int num_people; // 4 bytes on our platform
int start_time; // 4 bytes on our platform
int num_daze_rows; // 4 bytes on our platform
int num_daze_cols; // 4 bytes on our platform
char* name; // 8 bytes on our platform
char** daze; // 8 bytes on our platform
} Party;
void _print_party(Party* a_party);
int main(int argc, char* argv[]) {
int num_rows = 4;
int num_cols = 4;
Party* party = malloc(sizeof(*party) + // struct object itself
sizeof(*party -> daze) * num_rows + // row addresses
sizeof(**party -> daze) * num_cols * num_rows); // rows (chars)
party -> name = "Birthday"; // name of party (on data segment)
party -> num_people = 50; // # of people
party -> start_time = 11; // start time
party -> num_daze_rows = num_rows; // # of rows in the daze
party -> num_daze_cols = num_cols; // " " cols " " "
party -> daze = (void*)(party + 1); // byte right after struct
char* beginning_of_rows = (void*)(party -> daze + num_rows);
for(int i = 0; i < num_rows; i++) { // for each row
party -> daze[i] = beginning_of_rows + num_cols * i; // set address of this row
memcpy(party -> daze[i], "****", num_cols); // set content of this row
}
_print_party(party); // Print the party
free(party); // Now tear it all down.
return EXIT_SUCCESS;
}
void _print_party(Party* a_party) {
printf("Party name: %s\n", a_party -> name);
printf("# of people: %d\n", a_party -> num_people);
printf("Start time: %d\n", a_party -> start_time);
// Print the daze (2-dimensional array of "*")
printf("Daze:\n");
for(int row_idx = 0; row_idx < a_party -> num_daze_rows; row_idx++) {
for(int col_idx = 0; col_idx < a_party -> num_daze_cols; col_idx++) {
fputc(a_party -> daze[row_idx][col_idx], stdout);
}
fputc('\n', stdout);
}
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2017 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.