简体   繁体   中英

Why compilation fails when I initialize one pointer string to another non pointer string?

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'

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM