我的程序在Linux下用g++编译时,出现类型强制转换错误怎么班?

sintony 2002-04-22 08:26:27
我有一段在SunOS下编译正常的程序,在Linux下用g++编译,发现cannot convert `const char *' to `char *'的错误。我怎么样能不改源代码,解决这个问题?
...全文
485 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
ttyy 2002-04-23
  • 打赏
  • 举报
回复
是否加了:
#include <string.h>
shornmao 2002-04-23
  • 打赏
  • 举报
回复
下面的是我的代码,在g++-2.95-win32下完全没有任何问题,你的g++版本是什么?如果真的想兼容旧的代码,可以试一试-ansi和-fno-const-strings命令行参数。

#include <iostream>
void greeting(char *str);
int main()
{
greeting("shorn");
cin.ignore();
return 0;
}
void greeting(char *str)
{
cout<<"Hello,"<<str<<".\n";
}
prototype 2002-04-23
  • 打赏
  • 举报
回复
gcc is right. you should not do 类型强制转换 to a string
literal like "test" (if you write to a memory where "test"
is stored, the result is undefined).

btw, don't write a function like:
void A( char *pstr);

which indicates a bad design. always design it as:
void A( const char* pstr);
sintony 2002-04-23
  • 打赏
  • 举报
回复
这些我都知道,但是我现在就想不该源代码解决这个问题呀!
Last_Dodo 2002-04-23
  • 打赏
  • 举报
回复
那是Sun和MS的错。因为你的参数是char *所以你的函数可能对它做改动,而const char*是不允许你改内容的。即使强制转换也是很危险的,最好是把参数改成const char*或:
char buf[...];
strcpy(buf, "test");
然后传进去。
sintony 2002-04-22
  • 打赏
  • 举报
回复
"test"是const char*,但是我的函数的参数应该是char *,所以要强制转换!但是我不想这么做应为有很多地方。所以我觉得因该改一个编译器的标志能忽略这个错误。这个程序在SUNOS下和Windows下都是没有问题的!
winnest 2002-04-22
  • 打赏
  • 举报
回复
"test"肯定是const char*类型的啊,g++下是对的。
如果你的是C程序,用gcc而不用g++就可以了吧。
sintony 2002-04-22
  • 打赏
  • 举报
回复
不是呀!我有一个函数比如
void A( char *pstr);
可是我调用的时候用
A("test");
这样就会出现cannot convert `const char *' to `char *'
应该修改一下编译器的flag就好了,但是我不知道怎么修改
maoliao 2002-04-22
  • 打赏
  • 举报
回复
只要使用const_cast函数即可
xupingle 2002-04-22
  • 打赏
  • 举报
回复
把你的代码给出来看看。

70,023

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧