Author Topic: ProgEx04  (Read 2128 times)

0 Members and 1 Guest are viewing this topic.

Offline Frederick J. Harris

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 941
    • Frederick J. Harris
ProgEx04
« on: November 04, 2009, 04:07:23 AM »
Code: [Select]
/*
  ProgEx04.c

  In the previous three programs we used C arrays without really discussing them
  in great depth.  We stated that C uses arrays of characters to store strings.
  We further stated that strings must be terminated with a null byte to mark
  the end of the string.  Since arrays and loops are often associated together
  pretty closely in computer programming, lets see if we can display a string's
  characters and the addresses where the characters are stored so as to further
  familiarize ourselves with C programming constructs and addresses, particularly
  in reference to strings.

  The important fact you should gleen from this short program is that when the
  loop counter variable equals zero, szName[0] = szName = 2293600.  That's
  right!  An array name without the brackets is a pointer to the beginning of
  the array.

  Also note that a pointer variable can be explicitely declared and the address
  of a character string array stored in it.  That is the case below with pStr.
  Note the string can be output either way.
*/

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

int main(void)
{
 char szName[]="Fred Harris";
 char* pStr=szName;
 unsigned int i;

 puts("i\t&szName[i]\tszName[i]");
 puts("=================================");
 for(i=0;i<strlen(szName);i++)
     printf("%u\t%u\t\t%c\n",i,(unsigned int)&szName[i],szName[i]);
 printf("\n%s\t%u\n",szName,(unsigned int)szName);
 printf("%s\t%u\n",pStr,(unsigned int)pStr);
 getchar();

 return 0;
}

/*
i       &szName[i]      szName[i]
=================================
0       2293600         F
1       2293601         r
2       2293602         e
3       2293603         d
4       2293604
5       2293605         H
6       2293606         a
7       2293607         r
8       2293608         r
9       2293609         i
10      2293610         s

Fred Harris     2293600
Fred Harris     2293600
*/
« Last Edit: November 06, 2009, 10:36:23 PM by Frederick J. Harris »