Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does const char* get the pointer to a memory address?

Tags:

This may be simple question, but why does a const char* not need a memory address to point to?

Example:

const char* a = "Anthony"; 

and not:

const char *a = // Address to const char 

like any other types do?

like image 475
Weidelix Avatar asked Apr 18 '20 08:04

Weidelix


People also ask

What is const char * used for?

In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer. const char* and char const* says that the pointer can point to a constant char and value of char pointed by this pointer cannot be changed.

Does a pointer hold a memory address?

A pointer is a variable that points to another variable. This means that a pointer holds the memory address of another variable. Put another way, the pointer does not hold a value in the traditional sense; instead, it holds the address of another variable.

What is a const char pointer?

const char *ptr : This is a pointer to a constant character. You cannot change the value pointed by ptr, but you can change the pointer itself.

Do pointers point to memory?

A memory pointer (or just pointer) is a primitive, the value of which is intended to be used as a memory address; it is said that a pointer points to a memory address. It is also said that a pointer points to a datum [in memory] when the pointer's value is the datum's memory address.


1 Answers

You can imagine this declaration

const char* a = "Anthony"; 

the following way

const char string_literal[] = "Anthony";  const char *a = string_literal; 

That is the compiler creates an array of characters with the static storage duration that stores the string "Anthony" and the address of the first character of the array (due to the implicit conversion of array designators to pointers to their first characters) is assigned to the pointer a.

Here is a demonstrative program that shows that string literals are character arrays.

#include <iostream> #include <type_traits>  decltype( auto ) f() {     return ( "Anthony" ); }  template <size_t N> void g( const char ( &s )[N] ) {     std::cout << s << '\n'; }  int main()  {     decltype( auto ) r = f();      std::cout << "The size of the referenced array is "               << std::extent<std::remove_reference<decltype( r )>::type>::value               << '\n';      g( r );      return 0; } 

The program output is

The size of the referenced array is 8 Anthony 

The size of the string literal (of the array that stores the string literal) is equal to 8 because the string includes also the terminating zero character '\0'.

In the demonstrative program the expression

std::extent<std::remove_reference<decltype( r )>::type>::value 

may be substituted for just the expression

sizeof( r ) 
like image 50
Vlad from Moscow Avatar answered Sep 22 '22 18:09

Vlad from Moscow