如何在C++中正确使用char指向数组的指针?

stu*_*ash 0 c++ arrays pointers

我想拿起我的C++; 我对指针和引用有基本的了解; 但是当谈到指向数组的char指针时,它似乎对我没什么用.

我这里有一小段代码(省略include和namespace语句),我在下面的评论中包含了我的问题:

我至少经历了5个关于SO的问题,试图理解它; 但是那些答案并不是我所期望的答案,而是能够帮助理解那里的实际问题.

你能否从表面上深入解释我在下面评论过的问题(所以请不要直接深入研究)?

int main(){

    // 1 this is a char pointer to a char;
    char * c = new char;
    *c ='A';
    cout << c << endl; // this gives me memory address;
    cout << *c << endl;// this gives me the value in the memory address;


    // 2 this is a char array initialised to value "world";
    char d[6] = "world";
    cout << d[0] << endl; // this gives me the first element of char array;

    // 3 this is char pointer to char array (or array of char pointers)?
    char * str = new char[6];
    for(int i=0;i<6;i++){ // 
        str[i]=d[i];     // are we assigning the memory address (not value) of respective elements here? 
    }                   // can I just do: *str = "world"; what's the difference between initialising with value
                       // and declaring the pointer and then assign value?  

    char * strr = "morning";

    char b[6] = "hello";


    cout << b << endl;
    cout << (*str)[i] << endl; // why? error: subscripts requires array or pointer type
    cout << str[1] << endl;
    cout << (*strr)[1] << endl; // why? error: subscripts requires array or pointer type

}
Run Code Online (Sandbox Code Playgroud)

Som*_*ken 5

// 1这是一个指向char的char指针;

对.

// 2这是一个初始化为"world"的char数组;

对,"world\0"由编译器创建,并放在程序的只读存储区中.请注意,这称为字符串文字.然后将字符串复制到char数组d.

// 3这是char数组(或char指针数组)的char指针?

这是一个char指针yes,指向单个指针char.

//我们在这里分配各个元素的内存地址(不是值)吗?

不,您要分配元素的值.这是允许的,因为str[i]*(str + i)可以使用与指针相同的"数组样式"访问str.您循环遍历char已分配的各个s,new并为它们分配char数组中的字符值d.

//为什么?错误:下标需要数组或指针类型

因为你已经间接引用str(这是在6元开始指向char数组)用*它给你char,然后你尝试使用char像数组[1]这是没有意义的.*str会给你'w'(第一个元素).并且str[1]会给你*(str + 1)哪个是'o'(第二个元素),不要加倍.


一个小的大注释,字符串文字属于类型const char[],而不是char[],它们被放在只读存储器中,因此它们不能被程序改变(不要写入它们).

char * strr = "morning";
Run Code Online (Sandbox Code Playgroud)

这非常非常糟糕,它将a const char[]视为一种char[],现在已经在标准中弃用了一段时间,根据当前的标准,这甚至是非法的,但编译器仍然允许它出于某种原因.

因为编译器允许这样做,你可能会遇到一些令人讨厌的情况,比如试图修改字符串文字:

char * strr = "morning";
strr[0] = 'w'; // change to "worning"
Run Code Online (Sandbox Code Playgroud)

这将尝试写入只读内存,这是未定义的行为,可能/希望会给你一个分段错误.简而言之,使用适当的类型让编译器在代码到达运行时之前阻止你:

const char * strr = "morning";
Run Code Online (Sandbox Code Playgroud)

侧边注意:不要忘记delete你分配的任何东西new.