[Techtalk] getting the time as a string in c

Dan dan at cellectivity.com
Thu Sep 29 19:20:05 EST 2005

>     timestring[strlen(timestring)-1] = " ";

Just in case you haven't noticed this subtle point yet, in C you use
double quotes for a string and single quotes for a character:

  char *str = "a string";
  char ch = 'x';

The difference is much more fundamental than "a character is a string of
length one". A "char" is a primitive type like an "int"; in fact, in C
you can declare an "unsigned char", because a character is just a byte. 

A string is an array of characters. So the following is wrong:

  char *str = "a string";
  str[0] = "X";    /* Compiler complains here. */

That's because you must set str[0] to a character, not a string (array):

  str[0] = 'X'    /* Okay */

This is not just a matter of the compiler splitting hairs; characters
and strings behave very differently. For example, consider these two

  void setValues(char ch, char *str) {
    ch = 'X';       /* No effect outside the function. */
    strcpy(str, "foo");   /* Changes str outside the function. */

In effect, the character is passed by value and the string is passed by
reference (pointer). More accurately, the pointer is passed by value,
but what it points to is not copied and so is passed by reference.

No one ever had memory leak from a character; the problems come from

  Never ascribe to malloc() that which can adequately be explained
  by stupidity.
       - Jim Greenly, professor at Georgia Institute of Technology

More information about the Techtalk mailing list