Dean
Dean

Reputation: 1153

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,

Upvotes: 0

Views: 1270

Answers (6)

Vincenzo Pii
Vincenzo Pii

Reputation: 19805

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.

Upvotes: 1

Jeff Foster
Jeff Foster

Reputation: 44706

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.

Upvotes: 0

&#211;lafur Waage
&#211;lafur Waage

Reputation: 69991

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.

Upvotes: 2

Nick
Nick

Reputation: 25799

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!

Upvotes: 0

Xeo
Xeo

Reputation: 131789

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 chars are stored.

Upvotes: 0

Alexander Gessler
Alexander Gessler

Reputation: 46607

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 chars) which is convertible to a pointer to char. Therefore foo must accept char* rather than char because otherwise the types wouldn't match.

Upvotes: 3

Related Questions