简体   繁体   中英

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.

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 . Therefore foo must accept char* rather than char because otherwise the types wouldn't match.

char name is a single character

char* name is a pointer to a character in heap and if allocated correctly, can be an array of characters.

A string can be represented as an array of char(s). You can use the char * pointer to refer to that string. You could use char name with foo('c') , because that's a char.

char refers to a single character. char* is a pointer to an address in memory that contains a 1 or more characters (a string). If you are using C++, you might consider using std::string instead as it may be slightly more familiar.

Because a simple char is just one character, like 'c','A','0',etc. . char* is a pointer to a region in memory, where one or more char s are stored.

In C and C++ strings are quite often represented as an array of characters terminated by the null character.

Arrays in C and C++ are often represented as a pointer to the first item.

Therefore a string is represented as a pointer to the first character in the string and that is what char *name means. It means name is a pointer to the first character in the string.

You might want to read up a bit on pointers, arrays and strings in C/C++ as this is fundamental stuff!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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