Re: [CODE] char arrays

From: Jason Wilkins (fenix@IO.COM)
Date: 10/06/98

Andrew wrote:

> Hi all,
> I'm trying to design my own events system, using a queue type method.
> What I need to do is store certain information (in this case a command)
> into a char array. I'll give you an example...
> char eventarray[30000];
> void set_event(int time, long idnum, char *comm)
> {
>    eventarray[0] = *comm; /* Put's all of comm into 0 */
> }
> That's a part of my code. I can see what it's trying to do - it's trying
> to put a large string into the space designed to hold only a single byte.

It copies the first character of comm to the first character of event array.

eventyarray[0] and *eventarray are actually equivalent, they both have
type char,

you could have just as well written

*eventarray = *comm, or evenarray[0] = comm[0]

To copy a string you must use strcpy, this isn't C++ where you can override
the = operator to make it do strcpy for you.  C has no builtin string type.

> But I have seen bits of code that look like this....
> char stuff[] = {"Hello", "how", "are", "you?"};

This is an array of pointers to char, each constant "FOO" is an array of
characters and an array by itself is treated like a pointer, so

If I write "FOO" in my code, C treats it like a pointer to an array.

In other words, "FOO" is a shortcut for { 'F', 'O', 'O' }

> and then stuff[0] points to Hello, stuff[1] points to how etc. etc.

stuff[0] is a pointer, not a character.  stuff[0][0] would be the 'H'
in hello, it is a character.

> Any ideas?

To manipulate strings use the string library.  The only type that C knows
how to handle is characters.  The string library is designed to handle
arrays of characters that end in '\0'

char *foo = "Hello" is valid, because you can point foo at "Hello", they both

are considered to be pointers to a constant string.

char foo[] = "Hello" is basically the same thing.

char foo = "hello" is not valid, because foo is a character, "hello" is a
to a character (the first character of the array).

I remember having this confusion about C string when I first started, mainly
because I came from Basic.

> Andrew Ritchie.
> | Andrew Ritchie,
>      +------------------------------------------------------------+
>      | Ensure that you have read the CircleMUD Mailing List FAQ:  |
>      | |
>      +------------------------------------------------------------+

           Phoenix -- President of The Artistic Intuition Company
       Caelius * Mirror Reflex * Runica * X-Domain * Infinite Realms

     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     | |

This archive was generated by hypermail 2b30 : 12/15/00 PST