简体   繁体   English

Char指向匿名char数组的指针

[英]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. 它可以通过三个[0],三个[1] .....等访问。 How to access in the first case? 如何在第一种情况下访问? Thanks in advance... 提前致谢...

First of all char *three=(char*){'2','5','8','\\0'}; 首先是char *three=(char*){'2','5','8','\\0'}; is not valid C. To make a compound literal you must do like this: 无效C.要制作复合文字,您必须这样做:

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. 否则,您没有存储空间来存储新初始化的char数组。

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] . 它会产生相同的内存模式,因此您可以使用three[0]three[1]来访问单个字符。

(char*) {'2','5','8','\\0'}; is a pointer literal. 是一个指针文字。

As @Lundin wisely pointed out in comment: 正如@Lundin在评论中明智指出的那样:

It is not a valid compound literal. 它不是有效的复合文字。 6.7.9/11 "the same type constraints and conversions as for simple assignment apply". 6.7.9 / 11“与简单分配相同的类型约束和转换适用”。 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. 如果然后检查简单赋值6.5.16.1的规则,它不会将指针转换的整数列为有效形式。 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数组的复合文字,请使用

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

Also, note that according to N1570 6.5.2.5: 另请注意,根据N1570 6.5.2.5:

12 EXAMPLE 5 The following three expressions have different meanings: 12例5以下三个表达方式有不同的含义:

  "/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; 第一个总是具有静态存储持续时间并且具有char的类型数组,但不需要是可修改的; the last two have automatic storage duration when they occur within the body of a function, and the first of these two is modifiable. 当它们出现在函数体内时,最后两个具有自动存储持续时间,并且这两个中的第一个是可修改的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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