简体   繁体   中英

Char pointer to anonymous char array

I was wondering how to access individual elements in the below case:

char *three=(char*){'2','5','8','\0'};

If the assignment were like this:

char *three="258";

it can be accessed with three[0],three[1].....etc. How to access in the first case? Thanks in advance...

First of all char *three=(char*){'2','5','8','\\0'}; is not valid C. To make a compound literal you must do like this:

char *three=(char[]){'2','5','8','\0'};

When that is fixed, then there is no difference in how you access the data. In both cases you can use the [] operator to access data, it can be used on any pointer type. Where the pointer points at doesn't matter.

You can't initialize a pointer using

char *three=(char*){'2','5','8','\0'};

You have to do it like that: :

char three[] = {'2','5','8','\0'};

Otherwise, you have no storage space to store your newly initiatized char array.

Then, it is exactly the same.

It results in the same memory pattern, so you can access individual characters by using three[0] or three[1] .

(char*) {'2','5','8','\\0'}; is a pointer literal.

As @Lundin wisely pointed out in comment:

It is not a valid compound literal. 6.7.9/11 "the same type constraints and conversions as for simple assignment apply". If you then check the rules for simple assignment 6.5.16.1, it does not list integer to pointer conversions as a valid form. So there will be no runtime undefined behavior, since that line should not even compile

To create a compound literal of a char array, use

char *three=(char[]){'2','5','8','\0'};

Also, note that according to N1570 6.5.2.5:

12 EXAMPLE 5 The following three expressions have different meanings:

  "/tmp/fileXXXXXX" (char []){"/tmp/fileXXXXXX"} (const char []){"/tmp/fileXXXXXX"} 

The first always has static storage duration and has type array of char, but need not be modifiable; the last two have automatic storage duration when they occur within the body of a function, and the first of these two is modifiable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM