我有一些继承的FlexLM代码,它将整数转换为需要在32位和64位机器上工作的指针。使用scanf从程序的参数的argc填充整数以读取整数值。
我应该如何可靠地读取argc字符串以获得适合分配指针的值,以便它可以在32位和64位计算机上运行?
目前代码看起来像这样:
// 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\n", argv[i]);
} else {
lc_set_attr(lm_job, LM_A_MAX_LICENSE_LEN, (LM_A_VAL_TYPE)max);
}
}
[...]
起初我以为我可以使用uintptr_t
,但我如何让scanf
相应地知道尺寸?也许我应该使用%p
将其作为指针值读取,但是手册页让我怀疑它是否可靠运行:
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根据指针大小创建两个单独的版本,因为这对我来说似乎是一个丑陋的瑕疵。
答案 0 :(得分:5)
C99 inttypes.h
应该定义一个宏SCNuPTR
,它是正确的scanf格式说明符,用于平台上的uintptr_t参数。
uintptr_t intptr = 0;
sscanf(argv[i], SCNuPTR, &intptr);
答案 1 :(得分:0)
32位程序在64位架构中运行良好。
int address = 0x743358;
int *foo = reinterpret_cast<int*>( address );
我猜this就是你要找的东西。