Re: [gtk-list] strings



On Mon, 19 Jul 1999 21:26:33 -0400 (EDT), Bob P wrote:
> I come from a VB background, but have recently moved
> to gnome/gtk c.  i picked up on the c language pretty
> quickly (i did have some prior experience), but the
> only thing i'm not so sure with are strings.  in vb
> strings were rather simple.  basically, what's the
> difference between a string declared as:

Please notice that there is no such things as a string datatype in C;
character arrays are used instead.

> char some_string[10];

This is an array of characters. The index array starts at 0 and ends at 9.
It's a common beginners mistake to start at 1 and end at 10. If you do so,
you will get strange runtime errors, you are warned! Use like:

  some_string[0] = 'a';
  some_string[1] = 'b';
  some_string[2] = '\0';   /* note the trailing \0 */
  printf("%s\n", some_string);

> char *some_string;

This is an unitialized pointer to a char. You should initialize it like:

  char string1[10];
  char *string2;

  string2 = string1; /* string2 points to string1 */
  string2[0] = 'a';  /* string1[0] = 'a' */
  *string2 = 'b';    /* string1[0] = 'b' */

Or:

  char string1[] = "Hello, world!";
  char *string2 = NULL;

  /* allocate memory for string2, note the +1, that's for the trailing
   * '\0' that each string should have!
   */
  string2 = malloc(strlen(string1) + 1);
  /* check that we did get the memory */
  assert(string2 != NULL);

  /* copy string1 to string2 */
  strcpy(string2, string1);

  /* print it */
  printf("%s\n", string2);

  /* and free the memory */
  free(string2);

> gchar some_string[10];

This is an array of characters, too. A "gchar" is just a typedef for
"char", so this is the same as: char some_string[10];

> gchar *some_string;

Again, an unitialized pointer to a gchar.

> GString *somestring = NULL;

An initialized pointer to a GString. As this GString points to NULL,
you'll get a segnemtation fault if you use this string. You should
initialize it with g_string_new(). A GString is a VB like string datatype.
I haven't used it, so I can't tell you how it works (I'm familiar with the
standard C char pointers). For some documentation, see
http://www.gtk.org/rdp/glib/glib-strings.html .

As you are rather new to C, I advise you to get yourself a good C book and
read about pointers and arrays. Another good starting point is the
comp.lang.c FAQ, available at 
ftp://rtfm.mit.edu/pub/usenet-by-hierarchy/comp/lang/c/ .


Erik

-- 
J.A.K. (Erik) Mouw, Information and Communication Theory Group, Department
of Electrical Engineering, Faculty of Information Technology and Systems,
Delft University of Technology, PO BOX 5031,  2600 GA Delft, The Netherlands
Phone: +31-15-2785859  Fax: +31-15-2781843  Email J.A.K.Mouw@its.tudelft.nl
WWW: http://www-ict.its.tudelft.nl/~erik/




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]