【发布时间】:2013-01-19 06:34:02
【问题描述】:
我正在使用库中的函数,其中最重要的函数采用const short int* 类型的参数。我所拥有的是int *,我想知道是否有办法将int * 转换为const short int*。以下代码 sn -p 突出显示了我面临的问题:
/* simple program to convert int* to const short* */
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
void disp(const short* arr, int len) {
int i = 0;
for(i = 0; i < len; i++) {
printf("ith index = %hd\n", arr[i]);
}
}
int main(int argc, char* argv[]) {
int len = 10, i = 0;
int *arr = (int *) malloc(sizeof(int) * len);
for(i = 0; i < len; i++) {
arr[i] = i;
}
disp(arr, len);
return 0;
}
上面的代码sn -p 编译。
这是我迄今为止尝试过的:
1. 尝试了 c 风格的演员表。函数调用看起来像这样:disp((const short*) arr, len)。结果输出很奇怪:
ith index = 0
ith index = 0
ith index = 1
ith index = 0
ith index = 2
ith index = 0
ith index = 3
ith index = 0
ith index = 4
ith index = 0
- 尝试了 const-ness 演员表。函数调用如下:
disp(const_cast<const short*> arr, len);
这导致编译时出错。
我的问题:
1. 为什么方法一的输出这么奇怪?那边是怎么回事?
2. 我看到了一些使用方法 2 中的 const 强制转换来删除 const-ness 的示例。我不知道如何添加相同的内容。
3. 有没有办法将int* 转换为const short int*?
P.S:如果以前有人问过此类问题,请告诉我。我用谷歌搜索并没有找到任何具体的东西。
【问题讨论】:
-
你的目标应该是从你的代码中移除强制转换。
-
虽然我已经写了一个类似的答案,但如果您解释了您实际想要实现的目标,它可能会有所帮助 - 这听起来像是一个 XY 问题,您想做 X,您认为应该这样做由 Y 解决,因此您询问 Y。