Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use char a[] over char p* and vice versa?

Tags:

c

Lately I've been learning all about the C language, and am confused as to when to use

char a[];

over

char *p;

when it comes to string manipulation. For instance, I can assign a string to them both like so:

char a[] = "Hello World!";
char *p = "Hello World!";

and view/access them both like:

printf("%s\n", a);
printf("%s\n", p);

and manipulate them both like:

printf("%c\n", &a[6]);
printf("%c\n", &p[6]);

So, what am I missing?

like image 861
Nathan Bishop Avatar asked Dec 20 '22 10:12

Nathan Bishop


1 Answers

char a[] = "Hello World!";

This allocates modifiable array just big enough to hold the string literal (including terminating NUL char). Then it initializes the array with contents of string literal. If it is a local variable, then this effectively means it does memcpy at runtime, every time the local variable is created.

Use this when you need to modify the string, but don't need to make it bigger.

Also, if you have char *ap = a;, when a goes out of scope ap becomes a dangling pointer. Or, same thing, you can't do return a; when a is local to that function, because return value will be dangling pointer to now destroyed local variables of that function.

Note that using exactly this is rare. Usually you don't want an array with contents from string literal. It's much more common to have something like:

char buf[100]; // contents are undefined
snprintf(buf, sizeof buf, "%s/%s.%d", pathString, nameString, counter);

char *p = "Hello World!";

This defines pointer, and initializes it to point to string literal. Note that string literals are (normally) non-writable, so you really should have this instead:

const char *p = "Hello World!";

Use this when you need pointer to non-modifiable string.

In contrast to a above, if you have const char *p2 = p; or do return p;, these are fine, because pointer points to the string literal in program's constant data, and is valid for the whole execution of the program.


The string literals themselves, text withing double quotes, the actual bytes making up the strings, are created at compile time and normally placed with other constant data within the application. And then string literal in code concretely means address of this constant data blob.

like image 113
hyde Avatar answered Jan 11 '23 12:01

hyde