如何在C ++中将字符串转换为char *? [英] How to convert string to char * in C++?

查看:82
本文介绍了如何在C ++中将字符串转换为char *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将字符串转换为 char * 我正在使用以下方法,但它没有工作。

How can I convert a string in to char * I was using the following method, but it doesn't work.

在运行时出现以下错误:

At runtime it gives me the following error:


运行时检查失败#3-使用变量'url'时未初始化

Run-Time Check Failure #3 - The variable 'url' is being used without being initialized.

尽管我已将其初始化,如图所示在下面的代码中。

eventhough I have initialized it as shown in the code bellow. Can you please show me with an example?

    char* url;
    sup = "news"
    sup="http://www."+sup+"yahoo.com";
    strcpy(url, sup.c_str());

我在控制台中使用Microsoft Visual Studio 2010和C ++

I am using Microsoft Visual Studio 2010, C++ in console

推荐答案

strcpy 不会为您分配内存,您必须自己做,记住要为null留出空间终止符:

strcpy doesn't allocate memory for you, you must do it yourself, remembering to leave space for the null termination character:

char* url = new char[sup.length()+1];

char url[sup.length()+1];
//...
strcpy(url, sup.c_str());

在第一种情况下,请不要忘记删除[] 数组。仅当您的编译器支持C99可变长度数组作为扩展名时,第二种情况才有效。

In the first case, don't forget to delete[] the array. The second case will only work if your compiler supports C99 variable-length arrays as an extension.

这篇关于如何在C ++中将字符串转换为char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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