我正在尝试拿起我的 C++;我对指针和引用有基本的了解;但是当涉及到指向数组的字符指针时,似乎对我没有任何作用。
我在这里有一小段代码(省略了包含和命名空间语句),我将我的问题作为评论包含在下面:
我已经通过至少 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
}
// 1 这是一个指向 char 的 char 指针;
正确的。
// 2 这是一个初始化为值“world”的字符数组;
没错,“world\0”是编译器创建的,放在程序的只读内存区。请注意,这称为字符串文字。然后将字符串复制到char
数组中d
。
// 3 这是指向字符数组(或字符指针数组)的字符指针?
那是一个字符指针,是的,指向单个char
.
// 我们是否在这里分配了各个元素的内存地址(不是值)?
不,您正在分配元素的值。这是允许的,因为与指针str[i]
相同,*(str + i)
因此您可以使用相同的“数组样式”访问str
。您正在循环使用char
已分配的单个snew
并为它们分配char
数组中字符的值d
。
// 为什么?错误:下标需要数组或指针类型
因为您已经取消引用str
(它指向 6 元素char
数组的开头),*
它为您提供了char
,然后您尝试char
像使用[1]
没有意义的数组一样使用它。*str
会给你'w'(第一个元素)。并且str[1]
会给你*(str + 1)
'o'(第二个元素),不要加倍。
顺便提一下,字符串文字的类型是const char[]
,不是char[]
,它们被放置在只读内存中,因此它们不能被程序更改(不要写入它们)。
char * strr = "morning";
这是非常非常糟糕的,它将 aconst char[]
视为 a char[]
,这在标准中已经被弃用了一段时间,根据当前标准,这甚至是非法的,但由于某种原因,编译器仍然允许它。
因为编译器允许这样做,您可能会遇到一些令人讨厌的情况,例如尝试修改字符串文字:
char * strr = "morning";
strr[0] = 'w'; // change to "worning"
这将尝试写入只读内存,这是未定义的行为,可能/希望让您出现分段错误。长话短说,使用适当的类型让编译器在代码到达运行时之前阻止你:
const char * strr = "morning";
旁注:不要忘记delete
你分配的任何东西new
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句