Solution for Exercise 06_03-stringout.c

06_03-stringout.c

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

int main()
{
	char *alpha;
	int offset;
	
	/* allocate storage for 26 characters
	   plus the null character  */
	alpha = malloc( sizeof(char) * 27 );
	if( alpha==NULL )
	{
		fprintf(stderr,"Unable to allocate memory\n");
		exit(1);
	}

	/* assign the letters */
	for( offset=0; offset<26; offset++ )
		*(alpha+offset) = 'A' + offset;
	*(alpha+offset) = '\0';

	/* output */
	printf("%s\n",alpha);

	/* clean-up */
	free(alpha);
	return 0;
}

Output

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Notes

* This solution uses the pointer/offset method to access a buffer.

* Storage is allocated for 27 characters, which includes the 26 letters of the alphabet plus the null character. The address returned is stored in variable alpha: alpha = malloc( sizeof(char) * 27 );

* A for loop assigns the 26 letters. Variable offset is used both as the counting variable but also to set the offset in the buffer and the letter to place: *(alpha+offset) = 'A' + offset;

* After the loop is done, the value of offset references the end of the buffer. At this location, the null character is set: *(alpha+offset) = '\0';

* Because the buffer holds a legitimate string (characters terminating with the \0), it's output directly with a printf() function. The address stored in alpha is unchanged, and used as the base of the string.

* At the end of the code, the address stored in alpha is unchanged. It's freed, and the program quits.