Saturday, January 22, 2011

string.h

I was pondering about character arrays again.

I know I can do this:

char char_array[50] = "hello there\0";

and I'll have myself a nice little array of characters with enough space for 50 characters.

But what if I don't know what I want in there at the time of declaring it? I can't say:

char_array = "hello there";
or
char_array[0] = "hello there";

or anything like that. The first statement is the same as saying &char_array[0], and the second is trying to cram an address of a string literal into the first element of the character array, which you can't do.

I had thought that intuitively this would work:

char_array = "hello there";

since I know that char_array is a shorthand way of saying &char_array[0], but the compiler complains about mixing types. Specifically trying to assign a character pointer to a char array. I wonder if there is a clever casting trick that would fix that.... more experimenting is needed.

ANYWAYS.

I was trying to think of a way to assign a string to a character array after the fact, and thankfully there is a oft-used header called string.h that has a whole ton of string operation functions.

The one I needed was strcpy(), which does just what it says.

strcpy(char_array, "hello there");

copies "hello there" into my character array. K&R goes into detail about how to make your own version of this function (most of the examples in the book replicate standard library functions).

So there you go. Nice to have libraries.

No comments:

Post a Comment