2

I have a part of code, I don't understand how it works.

I have int Save(int _key, char *file); And this method Save accepts string as a char pointer Save(i, "log.txt");

So what happens at the end is inside the Save method I use fopen(file, "a+") and it works perfectly fine.

However I don't understand how it accepts "log.txt" for char *file.

user3002135
  • 237
  • 1
  • 4
  • 15

3 Answers3

8

The string literal "log.txt" has type char const[N], as per §2.13.5/8:

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

which decays to a pointer when passed as argument, as per §4.2/1:

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The result is a pointer to the first element of the array.

The reason char const* can be assigned to char* is mostly there for backward compatibility reasons and it has been deprecated in C++11.

Community
  • 1
  • 1
Shoe
  • 74,840
  • 36
  • 166
  • 272
  • is it `char const[N]` or `const char[N]`? can't remember if there's a difference for arrays(but I believe there is for pointers) – Alex Díaz Oct 07 '15 at 14:41
  • 1
    @AlejandroDíaz There's no difference. The difference if for when you have `const` before or after `*`, in which case it refers to the constness of the value or the pointer respectively. – Shoe Oct 07 '15 at 14:42
5

"log.txt" isn't a std:string is actually an array of chars containing {'l','o','g','.','t','x','t','\0'}, its type is const char[N] which decays to const char* hence the call to Save(i, "log.txt"); works.

The call works but the compiler prints a warning stating that converting from const char* to char* has been deprecated in C++03 and invalid in C++11.

Alex Díaz
  • 2,303
  • 15
  • 24
0

In C++ it is perfectly fine to initialize a character pointer with string literal. After initialization we can use that character pointer like an array as in:

{
  char *s="abc";
  cout<<s[0];
  cout<<s[1];
}
user3297764
  • 47
  • 1
  • 9