开发者

C notation: pointer to array of chars (string)

开发者 https://www.devze.com 2023-03-06 09:53 出处:网络
Why are pointers to arrays of chars (ie. strings) written as below: char *path Instead of:开发者_开发百科

Why are pointers to arrays of chars (ie. strings) written as below:

char *path

Instead of:开发者_开发百科

char *path[]

or something like that?

How could I create a pointer to a char and not a string?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消