如何使用scanf获取指针大小的整数? [英] How to get pointer sized integer using scanf?

查看:26
本文介绍了如何使用scanf获取指针大小的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些用于 FlexLM 的继承代码,它将整数转换为需要在 32 位和 64 位机器上工作的指针.整数正在从参数的 argc 填充到使用 scanf 读取整数值的程序中.

I have some inherited code for FlexLM that is converting an integer to a pointer that needs to work on both 32bit and 64bit machines. The integer is being filled in from argc of the arguments to the program using scanf to read the integer value.

我应该如何可靠地读取 argc 字符串以获得适合分配给指针的值,以便它在 32 位和 64 位机器上都能工作?

How should I reliably read the argc string to get a value suitable for assigning to a pointer so that it works on both 32bit and 64bit machines?

目前代码看起来像这样:

Presently the code looks something like this:

// FlexLM includes this:
typedef char * LM_A_VAL_TYPE; /* so that it will be big enough for */
                              /* any data type on any system */

// My main() includes this:
[...]
if (!strcmp(argv[i], "-maxlen")) {
  int max = 0;
  i++;

  if (i >= argc) {
    break;
  }
  sscanf(argv[i], "%d", &max);
  if (!max) {
    fprintf(stderr, "Error: -maxlen %s Invalid line length
", argv[i]);
  } else {
    lc_set_attr(lm_job, LM_A_MAX_LICENSE_LEN, (LM_A_VAL_TYPE)max);
  }
}
[...]

起初我想我可以使用 uintptr_t,但是我如何让 scanf 知道相应的大小?也许我应该使用 %p 将其作为指针值读取,但手册页让我怀疑它是否可靠工作:

At first I was thinking I could use uintptr_t, but how would I get scanf to know the size accordingly? Perhaps I should just read it as a pointer value using %p, but the man page gives me doubts about it working reliably:

   p      Matches an implementation-defined set of sequences, which shall be the
          same as the set of sequences that is produced by the %p  conversion
          specification  of  the  corresponding fprintf()  functions.  The
          application  shall  ensure that the corresponding argument is a pointer
          to a pointer to void. The interpretation of the input item is
          implementation-defined. If the input item is a value converted earlier
          during the same program execution, the pointer that results shall
          compare equal to that value; otherwise, the behavior of the %p
          conversion specification is undefined.

我宁愿不使用 #ifdef 根据指针大小制作两个单独的版本,因为这对我来说似乎是代码上的一个丑陋的疣.

I'd rather not use #ifdef to make two separate versions based on pointer size as that seems like an ugly wart on the code to me.

推荐答案

C99 inttypes.h 应该定义一个宏 SCNuPTR 这是正确的 scanf 格式说明符用于平台上的 uintptr_t 参数.

C99 inttypes.h is supposed to define a macro SCNuPTR which is the correct scanf format specifier to use for uintptr_t arguments on your platform.

uintptr_t intptr = 0;
sscanf(argv[i], SCNuPTR, &intptr);

这篇关于如何使用scanf获取指针大小的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆