[英]Why char *x not char x?
I've a code 我有一个密码
#include <iostream>
using namespace std;
void foo(char *name){ // ???
cout << "String: " << name << endl;
}
int main(){
foo("Hello");
return 0;
}
I don't know why I use "char name" won't work. 我不知道为什么我不能使用“字符名称”。 Please help.
请帮忙。
Cheers, 干杯,
char a
is just a single character, while char*
is a pointer to a sequence of characters - a string. char a
只是单个字符,而char*
是指向字符序列(字符串)的指针。
When you call foo("Hello")
, you pass in a string literal (strictly speaking an array of char
s) which is convertible to a pointer to char
. 当您调用
foo("Hello")
,您传入的字符串文字(严格来说是char
的数组)可以转换为char
的指针。 Therefore foo
must accept char*
rather than char
because otherwise the types wouldn't match. 因此
foo
必须接受char*
而不是char
因为否则类型将不匹配。
char name
is a single character char name
是单个字符
char* name
is a pointer to a character in heap and if allocated correctly, can be an array of characters. char* name
是指向堆中字符的指针,如果分配正确,则可以是字符数组。
A string can be represented as an array of char(s). 字符串可以表示为一个char数组。 You can use the char * pointer to refer to that string.
您可以使用char *指针来引用该字符串。 You could use
char name
with foo('c')
, because that's a char. 您可以将
char name
与foo('c')
,因为这是一个char。
char refers to a single character. char表示单个字符。 char* is a pointer to an address in memory that contains a 1 or more characters (a string).
char *是指向内存中包含一个或多个字符(字符串)的地址的指针 。 If you are using C++, you might consider using
std::string
instead as it may be slightly more familiar. 如果您使用的是C ++,则可以考虑使用
std::string
因为它可能会稍微熟悉一些。
Because a simple char
is just one character, like 'c','A','0',etc.
因为一个简单的
char
只是一个字符,例如'c','A','0',etc.
. 。
char*
is a pointer to a region in memory, where one or more char
s are stored. char*
是指向内存中存储一个或多个char
的区域的指针。
In C and C++ strings are quite often represented as an array of characters terminated by the null character. 在C和C ++中,字符串通常表示为以空字符结尾的字符数组。
Arrays in C and C++ are often represented as a pointer to the first item. C和C ++中的数组通常表示为指向第一项的指针。
Therefore a string is represented as a pointer to the first character in the string and that is what char *name
means. 因此,字符串被表示为指向字符串中第一个字符的指针,这就是
char *name
含义。 It means name
is a pointer to the first character in the string. 这意味着
name
是指向字符串中第一个字符的指针。
You might want to read up a bit on pointers, arrays and strings in C/C++ as this is fundamental stuff! 您可能想读一点C / C ++中的指针,数组和字符串,因为这是基本知识!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.