繁体   English   中英

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

[英]How do I correctly work with char pointer to array in C++?

我试图拿起我的C ++。 我对指针和引用有基本的了解; 但是当涉及到数组的char指针时,对我来说似乎没有任何用。

我在这里有一小段代码(省略了include和namespace语句),下面以注释的形式列出了我的问题:

我在SO上至少经历了5个其他问题,试图理解它。 但是这些答案不是我期望的,并且在一定程度上可以帮助您理解那里的实际问题。

您能否从地面深入一点来说明我在下面评论的问题(所以请不要直接深入探讨)?

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

}

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

对。

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

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

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

这是一个char指针,是的,指向单个char的指针。

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

不,您要分配元素的值。 这是允许的,因为str[i]*(str + i)相同,因此您可以使用与指针str相同的“数组样式”访问。 您正在遍历用new分配的单个char ,并在char数组d中为它们分配char的值。

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

由于已经取消引用str (其在6元素的开始指向char与阵列) *它给你char ,然后尝试使用char等以与阵列[1]这是没有意义的。 *str会给你'w'(第一个元素)。 str[1]会给你*(str + 1) ,即'o'(第二个元素),不要加倍。


一个小巧的注释,字符串文字的类型为const char[] ,而不是char[] ,它们被放置在只读存储器中,因此程序无法对其进行更改(请勿对其进行写入)。

char * strr = "morning";

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

因为编译器允许这样做,所以您可能会遇到一些讨厌的情况,例如尝试修改字符串文字:

char * strr = "morning";
strr[0] = 'w'; // change to "worning"

这将尝试写入只读内存,这是未定义的行为,可能会(希望)使您遇到分段错误。 长话短说,请使用适当的类型让编译器在代码到达运行时之前阻止您:

const char * strr = "morning";

旁注:不要忘记delete使用new分配的任何内容。

暂无
暂无

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

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