使用strdup

时间:2012-11-16 05:40:34

标签: c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{    
    char *s;
    s = strdup("foo");
    printf("%s\n", s);
    getchar();
    return 0;
}

看起来很无害,不是吗? 但我的IDE,即Dev-C ++,给出了以下警告: 警告:赋值使用整数而不使用强制转换

如果你想改变这样的代码,警告就会消失:

char *s;
s = (char*)strdup("foo");

enter image description here

任何人都可以帮我解释一下吗?

4 个答案:

答案 0 :(得分:7)

您正在使用Dev-C ++,但strdup不是C或C ++标准的一部分,它是POSIX函数。您需要定义正确的(根据您的IDE的文档)预处理器符号,以便由头文件声明strdup ...这是必要的,以便头文件在符合C或包含C时不会污染名称空间C ++源文件。

对于简单的便携式替代方案,请考虑

char* mystrdup(const char* s)
{
    char* p = malloc(strlen(s)+1);
    if (p) strcpy(p, s);
    return p;
}

或者,如果您知道strdup实际上在库中,您可以将其声明从string.h复制到您自己的源文件或标题中......或者使用手册页中的简单声明:

char *strdup(const char *s);

答案 1 :(得分:6)

那不对。 strdup已经返回char *。还有别的错。可能是因为您没有包含声明此函数的真实返回类型的正确头文件。

#include <string.h>

答案 2 :(得分:1)

你错过了#include <string.h>。在没有函数签名的情况下,编译器假定strdup返回一个int,因此返回警告。

答案 3 :(得分:1)

man strdup

你会得到以下的东西

#include<string.h>

char* strdup(const char * s);

所以strdup()返回char*那里没有任何问题 实际上在你的情况下它需要隐式声明strdup()所以默认返回类型是int因此你得到这个警告

include<string.h>

发出声明char* strdup(const char *);

在完成所有使用后,最后不要忘记free(s)

相关问题