You are here: Home / Past Courses / Fall 2011 - ECPE 177 / Projects / Malloc, structures, and casting

Malloc, structures, and casting

C source code icon main.c — C source code, 2 KB (2708 bytes)

File contents

/*
 * main.c
 *
 *  Created on: Oct 20, 2011
 *      Author: jshafer
 */

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct my_structure
{
	int data1;
	int data2;
	// The string will go here.  *But*, we don't know how big of a string
	// the user will enter, so we can't put it as part of our structure.  :-(
	char letter1;   // Best we can do is use this single character as a pointer to
					// the beginning of what will be an entire array of characters...
	// The
	// rest
	// of
	// the
	// string (array)
	// will
	// come
	// here
} __attribute__ ((packed)); // Prevent compiler from putting free space between variables


int main(void)
{
	// Temporary variables for user input
	int data1, data2;
	char data3[256];

	// Collect data from users into temporary variables
	printf("Enter integer 1: ");
	scanf("%i", &data1);
	printf("Enter integer 2: ");
	scanf("%i", &data2);
	printf("Enter string 1 (max of 255 characters): ");
	scanf("%255s", data3);

	// Print data for debugging
	printf("Data collected is: %i %i '%s'\n", data1, data2, data3);

	// Declare a new *empty* buffer in memory big enough to hold all
	// collected data so far.
	int total_data_size_in_bytes =
				sizeof(struct my_structure) // Big enough for data1 and data2
				- 1							// -1 because the struct has an extra char at the end
				+ strlen(data3)				// + enough space for the string
				+1; 						// + NULL char at end
	char* pointer_to_buffer_as_bytes = malloc(total_data_size_in_bytes);

	// Malloc() allocates memory and returns a pointer to the
	// buffer that can access it byte-by-byte (i.e. a pointer to an array of chars)
	// Cast a pointer to "my_structure" *over* the buffer created by malloc()
	//  so that you can access individual fields in the buffer.
	struct my_structure* pointer_to_buffer_as_struct;  // No structure here - just an empty pointer!
	pointer_to_buffer_as_struct = (struct my_structure*) pointer_to_buffer_as_bytes; // Casting

	// Copy data from the temporary variables into my new buffer
	// (which has convenient structure fields to make access easier)
	pointer_to_buffer_as_struct->data1 = data1;
	pointer_to_buffer_as_struct->data2 = data2;
	// strcpy() copies strings until it reaches the null character
	// (which is also copied)
	strcpy(&pointer_to_buffer_as_struct->letter1, data3);

	// Print data from structure for debugging
	printf("Data stored in struct is: %i %i '%s'\n",
			pointer_to_buffer_as_struct->data1,		// Integer
			pointer_to_buffer_as_struct->data2,		// Integer
			&pointer_to_buffer_as_struct->letter1);	// First character of full string

	// Free dynamic memory when finished
	free(pointer_to_buffer_as_struct);

	return 0;
}