Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between char and char* in C++?

Tags:

c++

pointers

Studing the code in Schaum's C++ book, i saw a lot of code using char*, int* etc. Doing the exercises i also saw that in the solutions there is char* and in my code i have used char (without the star).

I want to know what is the difference between a char and a pointer char - integer and a pointer integer ? Where should i use them ? What is exactly their meaning ?

like image 691
gujo Avatar asked Sep 26 '09 19:09

gujo


3 Answers

The variables with the * are pointers.

A 'normal' variable, for example a char or an int, contains the value of that datatype itself - the variable can hold a character, or an integer.

A pointer is a special kind of variable; it doesn't hold the value itself, it contains the address of a value in memory. For example, a char * doesn't directly contain a character, but it contains the address of a character somewhere in the computer's memory.

You can take the address of a 'normal' variable by using &:

char c = 'X';
char * ptr = &c;  // ptr contains the address of variable c in memory

And you get the value in memory by using * on the pointer:

char k = *ptr;  // get the value of the char that ptr is pointing to into k

See Pointer (computing) in Wikipedia.

like image 80
Jesper Avatar answered Sep 22 '22 08:09

Jesper


A pointer points to the memory address of a specific variable. Pointers can be quite hard to understand at first for some people, more information about it on wikipedia.

A char* is a pointer to a sequence of characters in memory, ended with a '\0'. A single char represents one character. An int* holds the memory address to an integer value.

Example:

int* x = new int();

We create a new integer variable on the heap, and the location in memory is saved in the pointer. The pointer now points to that part of the memory where the integer is located. If I would like to use the value of the integer that the pointer points to, then I would call:

int y = *x;

This dereferences the memory address; it gets the value behind the pointer. The value of y becomes the value of the data type behind the memory the pointer points to.

like image 43
Charles Avatar answered Sep 23 '22 08:09

Charles


char is a value type, so referencing a variable of that type gets a char. E.g.,

char ch = 'a';
cout << ch; // prints a

char* is a pointer to a char, typically used for iterating through strings. E.g.,

char* s = "hello";
cout << s; // prints hello
s++;
cout << s; // prints ello
like image 42
uncleO Avatar answered Sep 21 '22 08:09

uncleO