[英]deprecated conversion from string to char *
I want to get a filename from the command line or set a default name for that. 我想从命令行获取文件名或为此设置默认名称。 So, previously I used 所以,以前我用
static char *fName;
if (argc == 2 ) {
fName = argv[1];
}
else {
fName = "default_file.txt";
}
But for the else
, I get warning: conversion from a string literal to "char *" is deprecated
. 但是对于else
,我得到warning: conversion from a string literal to "char *" is deprecated
。 If I try something like this: 如果我尝试这样的事情:
static char fName [30] = "default_file.txt";
if (argc == 2 ) {
fName = argv[1]; //error
}
Now, I get error: expression must be a modifiable lvalue
. 现在,我得到一个error: expression must be a modifiable lvalue
。 So, how can I fix that? 那么,我该如何解决?
warning: conversion from a string literal to "char *" is deprecated 警告:不建议将字符串文字转换为“ char *”
This almost certainly means that you are using a C++ compiler. 这几乎可以肯定意味着您正在使用C ++编译器。 String literals (like "default_file.txt"
in your example) was once of type char[]
in C and C++ both. 字符串文字(例如您的示例中的"default_file.txt"
)曾经在C和C ++中都属于char[]
类型。 Writing to a string literal invokes undefined behavior. 写入字符串文字会调用未定义的行为。 Because of this, C++ changed the type of string literals to const char[]
. 因此,C ++将字符串文字的类型更改为const char[]
。 But in C, the type remains char[]
. 但是在C中,类型仍然是char[]
。 The warning is therefore an indication that you are using a C++ compiler for compiling C code, which is often not wise. 因此,该警告表明您正在使用C ++编译器来编译C代码,这通常不明智。
Note that it is however bad practice in C as well as C++, to have a non- const
-qualified pointer to a string literal. 请注意,在C和C ++中,对字符串文字使用非const
限定的指针是不好的做法。
Now, I get error: expression must be a modifiable lvalue. 现在,我得到一个错误:表达式必须是可修改的左值。
Because you can't assign a value to an array in run-time using assignment operators. 因为您不能在运行时使用赋值运算符将值分配给数组。 The C syntax does not allow this. C语法不允许这样做。 You would have to use memcpy, strcpy or similar. 您将不得不使用memcpy,strcpy或类似的东西。
Corrected code should be something like this: 更正后的代码应如下所示:
static const char* fName = "default_file.txt";
if (argc == 2 ) {
fName = argv[1];
}
This is fine for C and C++ both, though in C++ it is recommended practice to use std::string
instead. 这对C和C ++都很好,尽管在C ++中,建议您改用std::string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.