弃用转换错误

时间:2014-02-04 22:53:15

标签: c++ string sockets

我有以下代码段:

#include<stdio.h>    //scanf , printf
#include<string.h>  //strtok
#include<stdlib.h>  //realloc
#include<sys/socket.h>  //socket
#include<netinet/in.h> //sockaddr_in
#include<arpa/inet.h>   //getsockname
#include<netdb.h>   //hostent
#include<unistd.h>  //close

int get_whatthe_data(char * , char **);
int hostname_to_ip(char * , char *);
int whatthe_query(char * , char * , char **);
char *str_replace(char *search , char *replace , char *subject );

int main(int argc , char *argv[])
{
    char domain[100] , *data = NULL;

    printf("Enter domain name : ");
    scanf("%s" , domain);

    get_whatthe_data(domain , &data);

    return 0;
}

int get_whatthe_data(char *domain , char **data)
{
    char ext[1024] , *pch , *response = NULL , *response_2 = NULL , *wch , *dt;

    domain = str_replace("http://" , "" , domain);
    domain = str_replace("www." , "" , domain);

    dt = strdup(domain);
    if(dt == NULL)
        {
            printf("strdup failed");
        }
    pch = (char*)strtok(dt , ".");
    while(pch != NULL)
        {
            strcpy(ext , pch);
            pch = strtok(NULL , ".");
        }

并收到以下错误:

main.cpp: In function 'int get_whatthe_data(char*, char**)':
main.cpp:37:46: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
  domain = str_replace("http://" , "" , domain);

等等。

有人可以帮我解决这个问题。谢谢。

1 个答案:

答案 0 :(得分:6)

警告告诉您正在将"http://"等字符串文字分配给char*。由于您无法修改字符串文字,因此只应将其绑定到指向const char的指针。因此,请将str_replace签名更改为const char*

这是问题的简化版本:

char* word = "hello";       // BAD
const char* word = "hello"; // GOOD