String

From C

(Redirected from Strings)
Jump to: navigation, search

There is no string datatype in C.

What is often called a "string" in C is actually an array of characters terminated by a null ('\0') character. For example:

char foo1[] = "abcd";
char foo2[] = {'a', 'b', 'c', 'd', '\0'};

...in the above example both foo1 and foo2 are identical "C strings". This also means that you can't assign string values, like:

char foo_src[] = "abcd";
char foo_dst[] = "1234";

/* doesn't work */
foo_dst = foo_src;

...you have to assign each value in the source array to a value in the destination array. Eg.

char foo_src[] = "abcd";
char foo_dst[] = "1234";

foo_dst[0] = foo_src[0];
foo_dst[1] = foo_src[1];
foo_dst[2] = foo_src[2];
foo_dst[3] = foo_src[3];

...this code can also be generalized to...

unsigned int num = 0;

while (foo_src[num]) /* copy characters until the null character ('\0') in foo_src */
{
  foo_dst[num] = foo_src[num];
  ++num;
}
foo_dst[num] = 0; /* terminate foo_dst with a null */

...note that in the above both arrays are of size four and that if foo_dst was initially declared containing "xyz" then it wouldn't be possible to copy foo_src into it, as it would only have a size of three.

The above while loop is basically what strcpy() can do, although it is documented to work as an atomic unit so you can't do things like...

/* doesn't work */
strcpy(foo_src, foo_src + 1);


An array of characters will also often be called a buffer, and have a non-trivial amount of space allocated. This is often used in programs communicating over the network. Eg.

char  buf1[4096];
char *buf2 = malloc(4096);

copy_data_into_buf(buf1, 4096);

In the above buf1 and buf2 are of equal size (assuming the malloc call didn't fail), however sizeof(buf1) is 4096, and sizeof(buf2) is the size of a character pointer.

The biggest problem for the programer managing using C-style strings is a "buffer overflow", which is where memory is accessed outside of the range allocated. This is often why it is recommended that programs use a dynamic string API that cannot fail.

vstring is such an API.

See also StringsByExample.

External Links


Category Language, Category Pitfalls

Personal tools