• Welcome to Jose's Read Only Forum 2023.
 

ProgEx02

Started by Frederick J. Harris, November 04, 2009, 03:54:41 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Frederick J. Harris


/*   ProgEx02.c    >> Save As Main.c  */
#include <stdio.h>

int main(void)
{
char szBuffer[]="Frederick";

puts
(
 "  Strings and characters are unusual and specially important\n\
 in C.  There really isn't a special data type for strings, and\n\
 C just represents them as an array of characters with a null\n\
 byte at the end.  Note the declaration of szBuffer[] above.  The\n\
 compiler will allocate nine bytes for the letters plus one byte\n\
 for the null termination character in the program's data segment.\n\
 To print it to the screen use either the printf() function or the\n\
 puts() function.  These functions are in the C standard I/O library\n\
 stdio.h.  Here is an example:\n\n"
);
printf("  szBuffer=%s\n  ",szBuffer);
puts(szBuffer);
printf("\n");
puts
(
 "  Note the \%s in the quotes which tells the I/O library that\n\
 what is to be printed is a string of characters.  Now I'm going to\n\
 tell you something really interesting.  Even though szBuffer holds\n\
 a string of characters, it is possible to attempt to print szBuffer\n\
 using a percent u in the format string.  Let's try a little exper-\n\
 iment.  We'll attempt to print out szBuffer twice, but we'll vary the\n\
 format specifiers so that the first parameter in printf gets a percent\n\
 s associated with it, and the second one a percent u, e.g.,"
);
printf("\n\n  %s\t%u\n\n",szBuffer,(unsigned int)szBuffer);
puts
(
 "  Note in the output from above you would see something like this...\n\n\
 Frederick    4197564\n\n\
 The percent s told printf to interpret szBuffer as a string of\n\
 characters and the percent u told printf to interpret szBuffer as\n\
 an unsigned integer.  That's why we got a big number.  printf gave\n\
 us the address of the first byte of the string.  I don't know about\n\
 you but I find that kind of interesting!"
);
getchar();

return 0;
}