我目前正在尝试从几天前从我 friend 那里得到的一本书中学习 C++。我在书中看到一些代码作为我需要解决的测验。所以我试图解决它们,但我不确定我的假设是否正确。
这是第一个
char* r(char *g){ // can someone explain this line for me? I'm not sure what is it saying
char ch = 'B'; // is the code going to be correct if I changed char ch to char* ch?
return &ch; // since this is &ch, then the previous line should be char* ch, am I right?
}
第二个代码:
char* a;
a = new char[strlen(b)]; // will this line cause a compiling error just because b is undefined ? since there is no length for b because it's not even there?
strcpy(a,b); // since we're using strcpy() a and b has to be pointers am I right?
我不是在寻求答案,我需要有人告诉我是对还是错以及为什么。
最佳答案
char* r(char *g){ // can someone explain this line for me? I'm not sure what is it saying
声明一个函数,r
,它接受一个参数,一个指针g
来包含一个或多个字符的地址。
char ch = 'B';
声明一个类型为 char
的变量 ch
并为其赋值“B”。也就是说 - 它将包含一个数字,它是字母 B 在 ASCII 图表中的位置。它将包含 数字 66,但是当你打印出来时,它会产生字母 'B '. (参见 http://www.asciitable.com/)
这个变量很可能在栈上。它可能在寄存器中,但编译器通常很聪明,下一行将确保它在堆栈中。
return &ch;
在此上下文中,&
是 运算符的地址。
return address_of(ch);
因为 ch
是 char
类型,&ch
产生一个 char*
类型的值。
char* a;
声明一个没有初始值的变量a
。养成写作的习惯是一件坏事。
a = new char[strlen(b)];
你说 b
不存在,但我认为它应该是 char*
类型——指向一个或多个字符的指针。在 C 和 C++ 中,“C-String”是一个“char”值(字符)的数组,以值为 0 的字符终止(不是字符“0”,它的 ASCII 值为 48,而是 0,或“\0')。这称为“终止 nul”或“nul 字符”或“nul 字节”。
字符串 "hello"
实际上可以表示为数组 { 'h', 'e', 'l', 'l', 'o', 0 }
。对比 "hell0"
,它将是 { 'h', 'e', 'l', 'l', '0', 0 };
strlen
函数从调用它的地址开始计算字符数,直到找到 nul。如果 b 是“hello”的地址,strlen 将返回 5。
new 为一个对象分配内存,或者在本例中为 char 类型的对象数组,其数量是 strlen 的返回值。
size_t len = strlen(b);
char* a = new char[len];
在代码的这一点上,回想一下我关于终止 nul 的解释,并且 strlen 返回它找到 0 之前 的字符数。要存储 C 字符串,您需要字符数加上终止 NULL 的空间。
如果 b
是字符串“A”,它由一个字符 ('A') 和两个 *char*s - 'A' 和 0 组成。Strlen 返回字符数。
strcpy(a, b);
这会将 b
指向的字符复制到 a
的地址,*包括终止 nul。
这里的错误是你只为字符分配了足够的内存。
char* a = new char[strlen(b) + 1];
strcpy(a, b);
同样 - strlen 总是会返回长度 - 字符数,对于 nul,你总是想要比这多一个。
将是正确的 - 否则您将覆盖分配给您的内存并导致损坏。
--- 编辑 ---
将其中一些放在一起,在此处进行现场演示:http://ideone.com/X8HPxP
#include #包括
int 主要(){ char a[] = "你好"; std::cout << "a 开始为 ["<< a << "]\n";
// C/C++ arrays are 0-based, that is:
a[0] = 'H'; // changes a to "Hello"
std::cout << "a is now [" << a << "]\n";
std::cout << "strlen(a) returns " << strlen(a) << "\n";
// But that is based on counting characters until the 0.
a[3] = 0; // one way to write it,
a[3] = '\0'; // some people prefer writing it this way.
std::cout << "a changed to [" << a << "]\n";
std::cout << "strlen(a) is now " << strlen(a) << "\n";
return 0;
关于c++ - C++调试中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21275152/