0

s is pointing to "this is a string" but when I initialize it to t,it throws error C2440 so my question is Why compilation fails when I initialize one pointer string to another non pointer string?

#include<iostream>
using namespace std;
int main()
{
    char t="5d";
    char *s = "this is a string";
    cout<<s;
    cout<<&s;
    *s=t;
    cout<<s;
    cout<<&s;
    return 0;
}

error C2440: 'initializing' : cannot convert from 'const char [3]' to 'char'

4
  • Note that after you fix the compilation error, you will get a runtime error (memory access violation) on *s=t. Jan 29, 2015 at 19:21
  • 1
    std::string s = "this is a string";
    – crashmstr
    Jan 29, 2015 at 19:22
  • 3
    @barakmanos: You do not need to write the same comment on the question and all of the answers. We get it. Jan 29, 2015 at 19:26
  • 1
    @Ruchir Welcome to C++. Please use std::string instead of char*. Bjarne Stroustrup says it well: "If you don't want to use arrays and pointers, standard library strings and containers are (better) alternatives in many cases. If you use only low-level facilities, you are almost certainly wasting time and complicating maintenance without performance advantages" Jan 29, 2015 at 19:50

1 Answer 1

2

Because "5d" is a const char [3], not a char.

char t = "5d"; // Incompatible types here...

Try this instead:

char * t = "5d";
// ... or ...
const char t[] = "5d";

Perhaps this example helps:

const char t[] = "5d";
const char * s = "this is a string";
s = t;
2
  • 1
    And the following problem will be a memory access violation during runtime at *s=t. Jan 29, 2015 at 19:23
  • 2
    @barakmanos: sure, I'm just literally answering OP's question about the compilation error.
    – maerics
    Jan 29, 2015 at 19:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.