Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const char myVar* vs. const char myVar[] [duplicate]

Tags:

c++

c

Possible Duplicate:
Difference between using character pointers and character arrays

What's the difference between:

const char* myVar = "Hello World!";
const char  myVar[] = "Hello World!";

If there is one?

like image 521
John Humphreys Avatar asked Aug 16 '11 17:08

John Humphreys


2 Answers

The pointer can be reassigned, the array cannot.

const char* ptr = "Hello World!";
const char  arr[] = "Hello World!";

ptr = "Goodbye"; // okay
arr = "Goodbye"; // illegal

Also, as others have said:

sizeof(ptr) == size of a pointer, usually 4 or 8
sizeof(arr) == number of characters + 1 for null terminator
like image 120
Benjamin Lindley Avatar answered Oct 06 '22 18:10

Benjamin Lindley


First is a pointer.
Second is an array.

Size of all pointers in an system will be the same.
Size of the array in second declaration is same as the size of the string literal plus the \0.

You can point the first pointer to any other variable of the same type.
You cannot reassign the array.

like image 34
Alok Save Avatar answered Oct 06 '22 17:10

Alok Save