1

在 Ubuntu 10.04.2 x86_64 上使用 gcc 4.4.3 编译我收到以下警告:

warning: comparison between pointer and integer

对于这一行:

if (strptime(date_time, "%d-%b-%y %T", &tm) == NULL) {

如果我将 NULL 更改为 0,警告就会消失。但是 strptime 的手册页指出它在错误时返回 NULL。我包括<time.h>#define __USE_XOPEN 1上一行。我也试过了#define _XOPEN_SOURCE

感谢您的时间。

编辑

完整的包括:

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

#define __USE_XOPEN 1 /* needed for strptime */
#include <time.h>

#include <arpa/inet.h>
#include <errno.h>

#include "recv.h"
#include "tcp.h"
#include "types.h"

编辑

以下代码给出了相同的警告:

#define __USE_XOPEN 1 /* needed for strptime */
#include <time.h>

#include <stdio.h>

int main()
{
    struct tm tm;
    char date_time[] = "3-May-11 12:49:00";

    if (strptime(date_time, "%d-%b-%y %T", &tm) == NULL) {
        fprintf(stderr, "Error: strptime failed matching input\n");
    }

    return 0;
}

编辑编辑

但是将其更改为 _XOPEN_SOURCE 有效!并将定义移动到程序顶部修复了原始文件。

4

4 回答 4

3

根据POSIX 文档strptime<time.h>.

你需要

#define _XOPEN_SOURCE
/* other headers, if needed, after the #define
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
*/
#include <time.h>

在范围内有一个正确的原型。

如果没有原型,编译器会假定函数返回一个int.

于 2011-05-03T20:26:21.793 回答
2

[在发布完整包含块后编辑]

您使用了错误的功能选择宏,并且您在错误的位置进行操作。
#define __USE_XOPEN 1仅当 glibc 在内部执行时才有效,而不是在您执行时。
#define _XOPEN_SOURCE是您应该使用的,但只有将它放在所有 #includes 系统标题之前才有效。

此外,您的代码显示出糟糕的风格:在 an 内显式比较 NULL(或 0)if是一种不好的代码气味。你应该这样写:

if (!strptime(...))

此外,理性的人可能不同意这一点,但我根本不相信使用 NULL。在 C 中,0 是一个非常好的空指针常量,除非在非常不寻常的条件下——在这些条件下NULL 也不起作用。(C++ 中的情况有所不同。)

于 2011-05-03T20:33:22.437 回答
2

我想您收到该警告是因为strptime未声明。(没有声明,strptime默认返回int.)正如您已经猜到的,这可能是由于缺少#define _XOPEN_SOURCE.

以下程序在 Ubuntu 10.04.2 LTS 上使用“gcc”不产生任何警告。这是你的程序的样子吗?

#define _XOPEN_SOURCE
#include <time.h>

int main() {
  struct tm tm;
  char date_time[] = "Monday morning";
  if (strptime(date_time, "%d-%b-%y %T", &tm) == NULL) {
  }
  return 0;
}

编辑 您不能定义 __USE_XOPEN。您必须定义 _XOPEN_SOURCE。从 linux 手册页,正确的用法是:

#define _XOPEN_SOURCE
#include <time.h>
于 2011-05-03T20:35:43.840 回答
0

简单的。将其与 0 进行比较。 if strptime(date_time, "%d-%b-%y %T", &tm) == 0

于 2013-05-31T14:44:20.627 回答