将int*转换为const short int*

Sri*_*ram 2 c++ int pointers casting

我正在使用库中的函数,其中最重要的函数接受类型的参数const short int*.我所拥有的是,int *并且想知道是否有一种方法可以int *投入到const short int*.以下代码段突出显示了我面临的问题:

/* 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;
    }
Run Code Online (Sandbox Code Playgroud)

上面的代码片段编译.这是我到目前为止所
尝试的: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 
Run Code Online (Sandbox Code Playgroud)
  1. 尝试了常数演员.函数调用看起来像:
    disp(const_cast<const short*> arr, len);
    这导致编译时出错.

我的问题:
1.为什么方法1中的输出如此奇怪?那边发生了什么?
2.我看到了一些使用方法2中的const转换删除常量的示例.我不知道如何添加相同的内容.
有没有办法把一个人int*变成一个const short int*

PS:如果之前有过这样的问题,请告诉我.我用Google搜索并没有发现任何具体内容.

Oli*_*rth 5

通常,从int *to转换short *将不会产生有用的行为(实际上,如果您尝试取消引用结果指针,它可能会导致未定义的行为).它们指向基本不同的类型.

如果你的函数需要指向一堆shorts 的指针,那么你需要提供它.您需要创建一个数组short,并从原始数组中填充它.


Pet*_*ker 5

强制转换几乎总是设计问题的征兆。short*如果您有一个需要 a (或其他)的函数const,则需要使用 a 来调用它short*。因此,不要分配 的数组int,而是分配 的数组short

当您将 an 转换int*为 a时short*,您是在告诉编译器假装 theint*实际上是指向 的指针short。它会这样做,但是对编译器撒了谎,你要对后果负责。