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 66 67 68 69 70 71 72 73 74 75 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* This structure is somewhat similar to the maze used in the homework.
*
* This version uses an alternate way of initializing the struct object. This
* might be considered tidier by some. Regardless, it illustrates how objects
* on stack and be copied to the heap with just one assignment.
*/
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[]) {
Party temp_party = {
.name = "Birthday", // name of party (on data segment)
.num_people = 50, // # of people
.start_time = 11, // start time
.num_daze_rows = num_rows, // # of rows in the daze
.num_daze_cols = num_cols, // " " cols " " "
.daze = NULL
};
Party* party = malloc(
sizeof(*party) + // struct object itself
sizeof(*party -> daze) * temp_party.num_daze_rows + // row addresses
sizeof(**party -> daze) * temp_party.num_daze_rows * temp_party.num_daze_cols // rows
);
// Initialize everything except the daze from the temporary object on the stack.
*party = temp_party; // copy entire object in one assignment statement
// Initialize the daze, addresses of rows
party -> daze = (void*)(party + 1); // byte right after struct
// Initialize the daze rows (arrays of chars)
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.