C notation: pointer to array of chars (string)
Solution 1
char *path
is not a pointer to a string, it is a pointer to a char
.
It may be the case that char *path
semantically points to a "string", but that is just in the interpretation of the data.
In c, strings often use char *
, but only under the assumption that the pointer is to the first character of the string, and the other characters are subsequent in memory until you reach a null terminator. That does not change the fact that it is just a pointer to a character.
Solution 2
char *path
is a pointer to char. It can be used to point at a single char as well as to point at a char in a zero-terminated array (a string)
char *path[]
is an array of pointers to char.
A pointer to an array of char would be char (*path)[N]
where N (the size of the array) is part of the pointer's type. Such pointers are not widely used because the size of the array would have to be known at compile time.
Solution 3
char *path[]
is an array of pointers. char *path
is a single pointer.
How could I create a pointer to a char and not a string?
A 'string' in C is simply a pointer to a char
that has the convention of being the start of a sequence of characters that ends in '\0'. You can declare a pointer to a single char
the same way, you just have to take care to use it according to the data it's actually pointing to.
This is similar to the concept that a char
in C is just an integer with a rather limited range. You can use that data type as a number, as a true/false value, or as a character that should be displayed as a glyph at some point. The interpretation of what's in the char
variable is up to the programmer.
Not having a first class, full-fledged 'string' data type is something that distinguishes C from most other high level languages. I'll let you decide for yourself whether it distinguishes C in a good or a bad way.
Admin
Updated on September 15, 2020Comments
-
Admin over 3 years
Why are pointers to arrays of
char
s (ie.string
s) written as below:char *path
Instead of:
char *path[]
or something like that?
How could I create a pointer to a
char
and not astring
? -
Braden Best over 7 yearsSpeaking on the question title, is there a use for
char (*ptr)[]
? I can't seem to think of a situation where it'd be useful, especially compared to achar *ptr[]