Solution for Exercise 06_05-alphaoutput.c

06_05-alphaoutput.c

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

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

	/* assign the letters */
	for( ch='A'; ch<='Z'; ch++ )
	{
		*a = ch;
		a++;	/* increment 'a', not 'alpha' */
	}
	*a = '\0';

	/* output */
	a = alpha;	/* re-initialize 'a' */
	while( *a != '\0' )
		putchar( *a++ );
	putchar('\n');

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

Output

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Notes

* The only difference between this solution and 06_04-twopoitners.c (presented in the book) is found below the comment /* output */. In the original code, a printf() statement at this location output the string held in variable alpha.

* Before output, pointer variable a must be initialized: a = alpha No & (address-of) operator is required as both variables are pointers.

* With the address of pointer variable a reset, the while loop can process the string. The loop repeats until the value of *a is equal to the null character: while( *a != '\0' )

* For each iteration of the loop, the character referenced at address a is output: putchar( *a++ );

* The * (dereferencing) operator binds to variable a first, which obtains the value (character). Then the increment operator affects the value of pointer a, the address. I occasionally write this expression as *(a++) to keep my brain from melting, though the parentheses are unnecessary.