#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: %sn",preorden);
printf("The inorden is: %sn",inorden);
post(preorden,inorden,postorden,aux);
postorden[aux]=' ';
printf("The postorden calculated is: %sn",postorden);
free(postorden);
}
else{
fprintf(stderr,"Whithout memoryn");
return 1; // return 1
}
return 0;
}
错误在第5行和第6行编译器说:不推荐使用从字符串常量到"char*"的转换[-Wwrite strings]
您的代码很少有问题,首先是这个
char *preorden="GEAIBMCLDFKJH";//line 5
如果在C
中使用-Wwrite-strings
标志编译,则强制编译器发出如下警告
不赞成从字符串常量转换为"char*"[-Wwrite strings]
因为存储在主内存的只读部分中的字符串文字GEAIBMCLDFKJH
,即它指向的指针,该内容是可读,因此使用const char*
而不是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*
,它会自动安全地升级为任何其他指针类型,Read Do I强制转换mallock的结果?。例如
postorden = malloc(aux * sizeof(*postorden));//use of malloc function
同样在这里(这一点是关于下一行的错误评论,请不要介意(
aux=strlen(preorden);//convert to string
strlen(preorden)
返回preorden
指向的字符串的长度,并被分配给aux
,而不是注释中所写的(转换为字符串(。
并将post()
定义更改为
void post(const char *pre, const char *in, char *pos,int n) {
/* some code*/
}
出现消息"不赞成从字符串常量转换为'char*'[-Wwrite strings]",因为该代码被编译为C++代码,该代码与C.在字符串文本和指针转换方面有不同的规则
这可以通过将代码编译为C代码来解决,也可以通过向char *
插入显式强制转换来解决。