Addresses, Pointers, Arrays and Strings - Arrays of Strings

Chapter chap6 section 14

It is important to realise that a string constant such as

"hello, world"

is really a constant of type pointer to character that points to the system place where the actual string is stored. It is possible to have aggregates of strings which will, of course, really be aggregates of pointers to char. The following program, called stall1, demonstrates the point.
main()
{
	char	*days[] = {
		"Sunday",
		"Monday",
		"Tuesday",
		"Wednesday",
		"Thursday",
		"Friday",
		"Saturday"
			};
	char	*dname;
	int	nday;
	printf("Enter day of week [1-7] ");
	scanf("%d",&nday);
	dname = days[nday-1];
	printf("That is %s\n",dname);
}
		
A typical dialogue is shown below
$ stall1
Enter day of week [1-7] 4
That is Wednesday
bash$ stall1
Enter day of week [1-7] 2
That is Monday
$
The final 2 lines of code could have been replaced by the single line

printf("That is %s\n",ndays[n-1]);

The relationship between string constants, pointers and aggregates is well illustrated by the following program, which prints out a string constant backwards.
main()
{
        int     i=4;
	char	c;
        do
        {
		c = "hello"[i];
                printf("%c",c);
                i--;
        } while(i >= 0);
        printf("\n");
}
The output was
olleh
The key to understanding this is to remember that a string constant, such as "hello" in this case, is really the address of the place where the actual string is stored, the index operator can then, quite naturally, be associated with such an address.

The next program devlops the idea rather more obscurely. The purpose of the program, called stall2, is to display an integer in hexadecimal notation.

main()
{
	int	i;
	unsigned	int	m;
	printf("Enter an integer ");
	scanf("%d",&i);
	m = i;
	i = 0;
	do
	{
		printf("%c","0123456789abcdef"[m>>28]);
		m <<= 4;
	} while(++i<8);
	printf("\n");
}
A typical dialogue is given below.
$ stall2
Enter an integer 10
0000000a
$ stall2
Enter an integer 33
00000021
$ stall2
Enter an integer -9
fffffff7
$
The code will repay careful study. The string constant

"0123456789abcdef"

is, of course, the address of the start of an aggregate so the index operator may properly be used in this context. The value of the expression

m>>28

is simply the most significant half-byte of the (shifted) value of m which is used as index to select the relevant character from the string. Finally

m <<= 4

shifts the bit pattern 4 bits to the left so that progressively less significant half-bytes become the most significant half-byte after evaluation of "m>>28". It is essential that "m" be unsigned otherwise the shift operations would not work correctly.

The use of printf() or some other library function is a much more obvious and straightforward way of coding this conversion but it may well be useful if only a limited amount of memory is available for storing the code.


Library string handling function