在Schaum的C++书中学习代码,我看到很多代码使用char*,int*等.做练习我也看到在解决方案中有char*而在我的代码中我使用了char(没有星号).
我想知道char和指针char之间的区别是什么 - 整数和指针整数?我应该在哪里使用它们?他们的意思究竟是什么?
带有*指针的变量.
"普通"变量(例如char或int)包含该数据类型本身的值 - 该变量可以包含字符或整数.
指针是一种特殊的变量; 它不包含值本身,它包含内存中值的地址.例如,a char *不直接包含字符,但它包含计算机内存中某处字符的地址.
您可以使用以下方法获取"正常"变量的地址&:
char c = 'X';
char * ptr = &c; // ptr contains the address of variable c in memory
Run Code Online (Sandbox Code Playgroud)
并且通过使用*指针获得内存中的值:
char k = *ptr; // get the value of the char that ptr is pointing to into k
Run Code Online (Sandbox Code Playgroud)
请参阅维基百科中的指针(计算).
char 是值类型,因此引用该类型的变量会得到 char。例如,
char ch = 'a';
cout << ch; // prints a
Run Code Online (Sandbox Code Playgroud)
char* 是指向 char 的指针,通常用于迭代字符串。例如,
char* s = "hello";
cout << s; // prints hello
s++;
cout << s; // prints ello
Run Code Online (Sandbox Code Playgroud)