0
#include<iostream>
using std::cout;
using std::endl;
int main()
{
    char name[] = "abcde";  
    //char *name = "abcde";
    cout << name<<"\n";
    //type casting to get the address of char array
    cout<<static_cast<void *>(name);   
    return 0;
}

NO error or warning
output: abcde
0x7fff1cea50c0
  • But when i use * operator instead of [ ] , it still gives output but with warning "deprecated conversion from string constant 'char*' " and output as abcde 0x400964
  • Why such different address 24 bit and 48 bit, and why the warning?
  • Using Codeblocks , OS:Ubuntu, 64-bit system
N. Raj
  • 319
  • 4
  • 14

2 Answers2

2

Warning means you assign a constant string to a writable pointer, in more details it's described, for example, here

If you aren't planning to write using this pointer it's sort of safe and the warning could be suppressed, but then again, why not make it const to avoid risk of shooting yourself in the foot?

As for the address, the difference comes from the fact that one is allocated on the stack, while other is in read-only-data section which rather far from each other

isp-zax
  • 3,833
  • 13
  • 21
0
char *name = "abcde";

Assigning a string literal (aka a const char[]) to a non-const char* pointer is deprecated in C++11, thus the warning.

This declaration sets name to point at the starting address of the string literal's character data.

String literals reside in read-only memory. Code will crash if it tries to write to read-only memory using a non-const pointer. Pointers to literal data should be declared as const, eg: const char *name = "abcde";


char name[] = "abcde";

Initializing a char[] buffer (const or otherwise) with a string literal is allowed, so no warning.

This declaration allocates name at runtime to the full length of the string literal and then copies the string literal's character data into it.


This explains the difference in address outputs. One is an address in read-only memory, the other is an address in stack memory.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 24 bit address on stack when using * operator and 48 bit on ROM when using [ ] operator . correct? – N. Raj Sep 21 '17 at 09:39
  • @N.Raj according to the **values** you showed in your question, it is the other way around. But note that **all** pointers in a 64bit executable are 64bit in **size**, regardless of their **values**. The **values** are chosen by the OS at runtime. Your use of `cout.operator<<(void*)` is simply omitting leading zeros. If you want to display leading zeros you have to [format the output manually](https://stackoverflow.com/a/24701069/65863). – Remy Lebeau Sep 21 '17 at 14:52