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

Re: OT: Language War (Re: "C" Manual)



On Fri, 04 Jan 2002 23:50:04 -0600, Gary Turner <kk5st@swbell.net> wrote:

[snip]
> >He did define a string.  In C++ there are 3 ways of defining a string
> >(in C there are 2).  There is "char[]", "char*" and "std::string".
> Isn't 'char*' redundant, since an array var is a pointer by definition?
> If I'm showing my ignorance again, I apologize.

A foo[] and foo* are not the same.  The first implies automatic
allocation for some number of "foo's", while the second is only
a pointer to foo. That an array decays to a pointer to it's first
element in function calls doesn't make it the same as a variable
declared as a pointer. For instance, trying to free() a pointer
to an array leads to UB. You also can't resize an array, which
is one of the reasons pointers to char are so common.  However,
there is a little trick that's guaranteed to always work:

 struct foo {
	size_t length;
	char str[1];
 };

 ...

struct foo * str_to_foo(char *a)
{
  size_t len = strlen (a);
  struct foo *bar = malloc (sizeof(struct foo) + len);
  if (bar) {
    bar->length = len;
    memcpy (bar->str, a, len);  /* bar->str now not NUL terminated */
  }
  return bar;
} 

The benefit is being able to use one malloc vs. two (for any similarly
arranged struct).  The idiom can be useful for reading/writing binary
files as well.

> >The latter is the best way because it provides the most protection.
> >
> I disagree.  He defined an array of characters, just as 
>     int a[] = 1,2,3;
> is an array of integers.
> To define a string he should say
>     char a[] = "bad string";
> or
>     char a[11]; 
> Either of these forms would give him a properly terminated 'string'.
> Without the terminating \0, string functions will go merrily gonzo.

Of course, the point of the example was that the array was *not*
NUL terminated as required by C "strings", and therefore passing
it to a function expecting a NUL terminated string, results in UB.

Also, "int a[] = 1,2,3;" will *not* do what you expect.  In fact,
it won't compile at all.  I think you meant "int a[] = {1,2,3};".

Is this still debian-user?  I'm having comp.lang.c flashbacks 8^)

-- 
Eric G. Miller <egm2@jps.net>



Reply to: