gpt4 book ai didi

c - 为什么我有错误 : deprecated conversion from string constant to 'char*' [-Wwrite-strings] in the line 5 and 6?

转载 作者:行者123 更新时间:2023-12-01 13:17:49 27 4
gpt4 key购买 nike

   #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
char *preorden="GEAIBMCLDFKJH";//line 5

上面一行错误

   char *inorden="IABEGLDCFMKHJ";//line 6

这一行有错误

   char *postorden;

这一行有错误

   void post(char *pre, char *in,  char *pos,int n)
{
int longIzqda;

if(n!=0){
pos[n-1]=pre[0];
longIzqda=strchr(in,pre[0])-in;
post (pre+1,in,pos,longIzqda);
post (pre+1+longIzqda,in+1+longIzqda,pos+longIzqda,n-1-longIzqda);
}
}



int main(int argc,char *argv[])
{
int aux;

aux=strlen(preorden);//convert to string
postorden=(char *)malloc(aux*sizeof(char));//use of malloc function
if (postorden){
printf("The preorden is: %s\n",preorden);
printf("The inorden is: %s\n",inorden);
post(preorden,inorden,postorden,aux);
postorden[aux]='\0';
printf("The postorden calculated is: %s\n",postorden);
free(postorden);
}
else{
fprintf(stderr,"Whithout memory\n");
return 1; // return 1
}

return 0;
}

错误在第5行和第6行编译器说:弃用了从字符串常量到“char*”的转换 [-Wwrite-strings]

最佳答案

您的代码几乎没有问题,首先是这个

char *preorden="GEAIBMCLDFKJH";//line 5

如果在 C 中使用 -Wwrite-strings 标志编译,强制编译器像下面这样警告你

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

因为字符串文字 GEAIBMCLDFKJH 存储在主内存的只读部分,即它指向的指针,该内容是只读,因此而不是 char* 使用 const char*。例如

char *preorden = "GEAIBMCLDFKJH";/* preorden is normal pointer but "GEAIBMCLDFKJH" is read only, hence error */

const char *preorden = "GEAIBMCLDFKJH"; /* const char *ptr means ptr contents is read only */

其次,这里

   postorden=(char *)malloc(aux*sizeof(char));//use of malloc function

不需要转换 malloc 结果,因为 malloc() 返回类型是 void*,它会自动安全地提升为任何其他指针类型,阅读 Do I cast the result of malloc? .例如

postorden = malloc(aux * sizeof(*postorden));//use of malloc function

也在这里(这一点是关于下面一行的错误评论,请不要介意)

   aux=strlen(preorden);//convert to string 

strlen(preorden) 返回 length of string 指向 preorden 并分配给 aux 不像写在评论中(转换为字符串)。

并将 post() 定义更改为

void post(const char *pre, const char *in,  char *pos,int n) {
/* some code*/
}

关于c - 为什么我有错误 : deprecated conversion from string constant to 'char*' [-Wwrite-strings] in the line 5 and 6?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53046814/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com