warning:deprecated conversion from string constant to 'char *'解决方案

指针定义字符串的一些问题 [Warning] deprecated conversion from string constant to char* —新人文 在学习指针定义字符串时,我遇到了 [Warning] deprecated conversion from string constant to ‘char*’ [-Wwrite-strings] 的困扰,为什么会有这个警告? 为了解决这个问题,我去查阅了很多资料,故在此写下我的第一篇博客,希望能够帮助到大家。 如有错误,希望大家指出。 在这之前,我觉得有必要先说一下指针和数组定义的字符串之间的一些区别 我们先看这样一段代码,大家也可以尝试着运行感受一下 #include<stdio.h> i 阅读详情

Linux 环境下当GCC版本比较高时,编译代码可能出现的问题

问题是这样产生的,先看这个函数原型:

void someFunc(char *someStr);

再看这个函数调用:

someFunc("I'm a string!");

把这两个东西组合起来,用最新的g++编译一下就会得到标题中的警告。

为什么呢?原来char *背后的含义是:给我个字符串,我要修改它。

而理论上,我们传给函数的字面常量是没法被修改的。

所以说,比较和理的办法是把参数类型修改为const char *。

这个类型说背后的含义是:给我个字符串,我只要读取它。

很自然的延伸一下。

如果我既要传字面常量又要传字符串变量怎么办呢?......重载

实验:

对deprecated conversion from string constant to 'char *'此类警告的详细解释

假定你想使用一个char*类型的变量,有时指向一个字符串,有时指向另外一个字符串。开始的代码就像这样:
char *msg;
msg = "hello";
msg = "good-bye";

编译器会对这段代码给出两段警示,说”deprecated conversion from string constant to 'char *'",意思就是说你没有能力修改字符串的内容。如果将代码写成这样,如:
char *msg = "hello";
*msg = 'j';
printf( "%s/n", "hello" );

编译器会通过编译,实际上会将msg指向的内容从"hello"转变为"jello", 正确的解决方法是将msg声明为一个指向不变字符串的指针:
const char  *msg;
msg = "hello";
msg = "good-bye";

这段代码可以成功编译,并且将msg指向的值如愿改变,但如果你将指针指向的指进行赋值:
*msg = 'j';
将会产生一个错误,不能修改一个字符串常量

注意如下的代码,此代码编译时不会出现警告也不会出现任何错误:
const char  *msg;
char   buf[ 10 ];   //注意不能使用char *buf;
sprintf( buf, "%03d/n", 7 );
msg = buf;

改变buf的内容是可以的,因为它并没有被声明为常量。在这种情况下,msg将指向一个字符串,"007/n". 像这种语句
*buf = 'x';
将会正确编译执行,但像
*msg = 'x';
将会产生一个警告,因为msg指向的内容不允许改变


还有一种方法是使用强制转换,使用强制转换意味着你清楚会出现什么情况,不需要编译器为你做出判断,例如下面的代码将不会产生警告:
char  *msg;
msg = (char *) "hello";


但一旦你使用强制转换,编译器对如下语句进行编译时,也不会出现错误或警告
*msg = 'j';

这个错误将一直存在,但并不会被发现,直到运行时。那时再找出错点就相当麻烦了,比编译器提醒你,麻烦多了。所以,最好不要对字符串使用强制转换。

Constant 指针

根据constant的位置不同,可以有以下四种情况:
const char* const msg_0;
const char       *msg_1;
char* const msg_2;
char       *msg_3;


其中,msg_0是一个constant指针指向一个const字符串。这个声明编译器会给出一个警告,因为msg_0的指向没有被初始化,而且之后的语句也无法对mg_0进行赋值,如
const char const *msg_0 = "hello";
会编译成功,但
*msg_0 = 'j';或者
msg_0 = "good-bye"; 将会产生错误

msg_1既可以指向一个const字符串,也可以指向一个可变的字符串,但是不能修改它所指向的字符串的内容。

编译msg_2这条语句,会出现和编译msg_0一样的错误。因为指针是一个常量,所以它应该首先被赋值。如果刚开始已经赋值,那么它可以对指向的字符串内容进行修改,如:
char        buf[ 10 ];
char * const msg_2 = buf;
这段代码里,msg_2指向buf[0],并且永远指向这个地址,不会改变;

对于msg_3,就没太多可以说的。你可以改变指针,也可以改变指针指向的内容

Dev C++中string和char的一些问题及deprecated conversion from string constant to ‘char*’ 最近在dev c++上写字符串程序。遇到一些问题,string和char都是字符类型的。但是在dev里面使用还有点差异。 关于string 首先,我先写了这个代码 #include<stdio.h> #include<string.h> int main(void) { string s = "hello"; printf("%s",s); return 0; } ... 阅读详情

相关推荐

【NCBI】SRA toolkit安装及使用-Windows&Linux版本

由于市面上的文章介绍SRA toolkit基本上都是基于Linux,而在windows下运行SRA toolkit基本上可以达到相同的效果且更为方便,故本文将分别阐明在Windows和Linux环境下SRA toolkit的安装及使用。

weixin_48076899的博客 2万+

warning: deprecated conversion from string constant to ‘char*’

环境:linux下使用g++编译报错:warning: deprecated conversion from string constant to ‘char*’意思:不接受字符串(string)转换为字符串常量(char*)报错代码:#include &lt;iostream&gt; using namespace std; void print(char *s) { cout&lt;&...

djw931017的博客 2368

【Python学习日记:PySide6】【持续更新】

说明:PySide6 是 Qt for Python 的一部分,是一个 Python 绑定库,可以用来创建跨平台的 GUI 应用程序。它将 Qt 框架的丰富功能带到了 Python 环境中,允许开发者使用 Python 编写 GUI 应用程序。

XLQ的博客 8047

deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]char *背后的含义是:给我个字符串,我要修改它。而理论上,我们传给函数的字面常量是没法被修改的。所以说,比较和理的办法是把参数类型修改为const char *。这个类型说背后的含义是:给我个字符串,我只要读取它。...

瞌睡的洋葱的博客 1163

在Ultralytics YOLO中添加/更换模块详细指南

使用参数继承 my_module_args: &my_args [64, 3, 0.5] # 定义参数模板 backbone: - [-1, 1, MyModule, *my_args] # 引用参数。

MR_Colorful的博客 2584

用GraphPad Prism直出单细胞亚群堆叠柱状图

用GraphPad Prism直出单细胞亚群堆叠柱状图

fivehuge的博客 4197

warning:deprecated conversion from string constant to 'char *'[-Wwrite-strings]解决方案

Linux 环境下当GCC版本比较高时,编译代码可能出现的问题 问题是这样产生的,先看这个函数原型: void someFunc(char *someStr); 再看这个函数调用: someFunc("I'm a string!"); 把这两个东西组合起来,用最新的g++编译一下就会得到标题中的警告。 为什么呢?原来char *背后的含义是:给我个字符串,我要修改它。 而理论上,我们...

dingzj2000的专栏 2万+

RT-DETR改进策略【Conv和Transformer】| HiLo注意力机制 通过分离处理图像的高频和低频信息,高效处理图像特征

本文记录的是利用改进检测模型,针对目标检测中面临的多尺度特征融合效率与长距离依赖建模难题,HiLo注意力模块的引入旨在通过频率解耦策略优化高分辨率特征处理,将高频细节(如目标边缘)与低频语义(如场景结构)分离建模,提升目标检测精度。Fast Vision Transformers with HiLo AttentionHiLo注意力模块的提出源于对传统自注意力机制局限性的反思。传统多头自注意力(MSA)在处理高分辨率图像时存在以下问题:HiLo将注意力模块分为高频(Hi-Fi)和低频(Lo-Fi)两个分支,

Limiiiing的博客 818

warning:deprecated conversion from string constant to 'char *' 解决方案2

#include using namespace std; int fuc(char *a) { cout << a << endl; } int main() { fuc("hello"); }

u013048416的专栏 771

华东理工大学计算机预推免面试

华东理工大学预推免面试经验分享

D1379951481的博客 1404

9.13华为OD机试真题 新系统 - 手机桌面整理 (Java/Py/C/C++/Js/Go)

华为OD机试真题 新系统【手机桌面整理】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试真题 【 手机桌面整理】多语言题解。

qq_45776114的博客 642

warning:deprecated conversion from string constant to 'char *' 解决方案

#include using namespace std; int fuc(char *a) { cout << a << endl; } int main() { fuc("hello"); } Linux 环境下当GCC版本比较高时,编译代码可能出现的问题 问题是这样产生的,先看这个函数原型: 1 v

sinat_31869361的博客 371

【2025国赛A题】A题烟幕干扰弹的投放策略思路+代码+论文

【2025国赛A题】A题烟幕干扰弹的投放策略思路+代码+论文

订阅付费专栏Matlab(奶茶价版),可赠送奶茶价版付费专栏指定代码1份; 867

android NDK开发遇到warning:deprecated conversion from string constant to 'char *'解决方案

Linux 环境下当GCC版本比较高时,编译代码可能出现的问题 问题是这样产生的,先看这个函数原型: void someFunc(char *someStr); 再看这个函数调用: someFunc("I'm a string!"); 把这两个东西组合起来,用最新的g++编译一下就会得到标题中的警告。 为什么呢?原来char *背后的含义是:给我个字符串,我要修改它。 而理论上,我们

JJMM2009的专栏 922

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 浅析命令行参数
下一篇: C指针小结1
zmrlinux
博客等级 码龄12年 409粉丝 327原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值