在下面的(C++)代码中,
char * type = "";
switch (mix_mode) {
case GO_HISTORY_VIDEO_MIX_VISUAL_GAS:
type = "visual gas";
break;
case GO_HISTORY_VIDEO_MIX_VISUAL:
type = "visual";
break;
case GO_HISTORY_VIDEO_MIX_GAS:
type = "gas";
break;
case GO_HISTORY_VIDEO_MIX_LARGE_IR_DIRECT:
type = "ir direct";
break;
case GO_HISTORY_VIDEO_MIX_LARGE_IR_FILTERED:
type = "ir filtered";
break;
}
strcpy(suffix, "avi");
snprintf(filename, sizeof(filename), "%s - (%s %s).%s", name_comp, type, uid, suffix);
Run Code Online (Sandbox Code Playgroud)
我有以下编译警告:
GO_C_MSDExportManager.cpp:192:31: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
char * type = "";
^
GO_C_MSDExportManager.cpp:195:12: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
type = "visual gas";
^
GO_C_MSDExportManager.cpp:198:12: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
type = "visual";
^
GO_C_MSDExportManager.cpp:201:12: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
type = "gas";
^
GO_C_MSDExportManager.cpp:204:12: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
type = "ir direct";
^
GO_C_MSDExportManager.cpp:207:12: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
type = "ir filtered";
Run Code Online (Sandbox Code Playgroud)
我看到char指针是不安全的,但是我不确定在这种情况下是否会出现问题,而type在任何其他地方都没有使用.
我确实知道做类似事情的可能性 *type = 'X';会很糟糕,因为它会改变字符串文字并可能导致我的机器崩溃.
问题:
char指针有什么问题?
const char * type = new char[20];摆脱警告是一个很好的解决方案吗?
字符串文字的类型是const char[],并注意:
在C中,字符串文字的类型为char [],可以直接分配给(非const)char*.C++ 03也允许它(但不赞成它,因为文字在C++中是const).没有强制转换,C++ 11不再允许这样的赋值.
然后
1. char指针有什么问题?
如你所说,char *可以改变字符串文字并导致UB.
您可以创建一个从字符串文字初始化的数组,然后稍后修改数组,例如:
char type[] = "something"; // type will contain a copy of the string literal
Run Code Online (Sandbox Code Playgroud)
2.Is const char*type = new char [20]; 摆脱警告的好方法?
这里不需要创建一个新数组,因为你只是改变了指针本身的值,而不是它指向的内容.你应该只改变typeto 的类型const char*,
const char * type = "";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3649 次 |
| 最近记录: |