如果const char *在函数调用中转换为char *,则可能出现任何问题 [英] Any possible issues if const char * is converted to char * in a function call

查看:150
本文介绍了如果const char *在函数调用中转换为char *,则可能出现任何问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在fun1()中我得到一个字符串,我需要将这个字符串数据传递给函数fun2(),它接受参数char *



function2 prototype is如下所示



void fun2(char * p);

我从fun1调用fun2,如下所示



void fun1()

{

fun2((char *)str.c_str());

}

从const char *到char *的转换是否有任何可能造成任何潜在问题

In fun1() I am getting a string and I need to pass this string data to a function fun2() which takes argument char *

function2 prototype is as below

void fun2(char *p);
I am calling fun2 from fun1 as below

void fun1()
{
fun2((char *)str.c_str());
}
Is there any chance from the conversion from const char * to char * does make any potential issues

推荐答案

是。

const char *无法转换为char *因为它会打开更改常量值的可能性:在这种情况下可能会改变(比方说)用户提示符来自hello user! HeLlO UsEr!并且在程序中途进行固定提示更改。

如果需要将const char *传递给带char *的函数,则需要分配一些char内存,并复制常量字符串进入它 - 然后你可以将非const副本传递给你的函数。
Yes.
A const char* can't be converted to a char* because it would open up the possiblity of changing the value of constants: in this case potentially changing (say) a user prompt from "hello user!" to "HeLlO UsEr!" and making the fixed prompt change half way through the program.
If you need to pass a const char* to a function taking a char*, you need to allocate some char memory, and copy the constant string into it - then you can pass the non-const copy to your function.


你可以通过简单地获取第一个字符的地址从C ++字符串中获取可修改的C字符串。使用



You can get a modifiable C string from a C++ string by simply taking the address of the first character. Use

void fun1()
{
    fun2(&str[0]);
}





(唯一的问题是如果fun2碰巧修改了其C字符串参数的终止空字符,则为null在这种情况下附加的C ++字符串是不可修改的)



(the only catch is if fun2 happens to modify the terminating null character of its C string argument, the null appended by the C++ string in this situation is not modifiable)


这篇关于如果const char *在函数调用中转换为char *,则可能出现任何问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆