如何在C ++中转换char*为const char*?为什么程序1可以运行,但是程序2不能运行?
编1(工作):
char *s = "test string";
const char *tmp = s;
printMe(tmp);
void printMe(const char *&buf) {
printf("Given Str = %s", buf);
}
Run Code Online (Sandbox Code Playgroud)
编2(无效)
char *s = "test string";
printMe((const char *)s); // typecasting not working
void printMe(const char *&buf) {
printf("Given Str = %s", buf);
}
Run Code Online (Sandbox Code Playgroud)
我收到的错误:
x.cpp:10:15: warning: conversion from string literal to 'char *' is
deprecated [-Wc++11-compat-deprecated-writable-strings]
char *s = "test string";
^
x.cpp:12:5: error: no matching function for call …Run Code Online (Sandbox Code Playgroud)