【问题标题】:Arrays of pointer dereferencing指针解引用数组
【发布时间】:2016-01-08 07:59:31
【问题描述】:

我想要一个名为 sortPointers() 的函数,它设置一个整数指针数组,以升序指向另一个数组的元素。

到目前为止我所做的是

      void sortP(int src[], int *ptrs[], int n)
 {
     int temp;
    for(int i = 0; i< n ; i++)
    {
        ptrs[i] = & src[i]; // assign the address of each number in the src[] to the array of pointers
    }

    while (1)
    {
        int flag = 0;
        for(int i = 0; i< n;i++)
            {
                    if ( *(ptrs[i]) > *(ptrs[i+1])) //bubble sort
                {
                     temp = *(ptrs[i]);
                     *(ptrs[i]) = *(ptrs[i+1]);
                     *(ptrs[i+1]) = temp;
                     flag = 1;
                }
            }
            if(flag == 0);
            break;
      }

      for(int i = 0; i< n;i++)
      {
          printf("%i\n",ptrs[i]);
      }
 }

在主函数中,我调用了这个函数

main()
{
    int a[5] = {5,4,3,2,1};
    int *ptrs[5]= {&a[0],&a[1],&a[2],&a[3],&a[4]};
 sortP(a, *ptrs, 5);

}

我的结果是地址,如果我想打印出指针指向的实际值 (1,2,3,4,5) ,我应该在 printf() 中更改什么?

谢谢

附:我之前尝试过 *ptrs[i] ,但是我得到了奇怪的数字,而不是 src[] 中的数字..

【问题讨论】:

  • printf("%i\n", *ptrs[i]);
  • 你为什么要sortP(a, *ptrs, 5),而它显然应该是sortP(a, ptrs, 5)?您的编译器不会对此发出警告吗?
  • @EOF umm 如果我输入“ptrs”而不是 *ptrs 它有错误...我正在使用代码块默认编译器
  • @bslqy "它有错误" -- 如果您遇到错误,请提及确切的错误。这个错误很有帮助。

标签: c arrays pointers


【解决方案1】:

查看注释:

void sortP(int src[], int *ptrs[], int n)
{
    int temp;
    for(int i = 0; i< n ; i++)
    {
        ptrs[i] = & src[i]; // assign the address of each number in the src[] to the array of pointers
    }

    while (1)
    {
        int flag = 0;

        // check if i < n-1, not n
        for(int i = 0; i< n-1;i++)
            {
                if ( *(ptrs[i]) > *(ptrs[i+1])) //bubble sort
                {
                     temp = *(ptrs[i]);
                     *(ptrs[i]) = *(ptrs[i+1]);
                     *(ptrs[i+1]) = temp;
                     flag = 1;
                }
            }
            if(flag == 0)
            break;
      }

      for(int i = 0; i< n;i++)
      {
          //*ptrs[i] instead of ptrs[i]
          printf("%i ",*ptrs[i]);
      }
}

int main(void)
{
    int a[5] = {5,4,3,2,1};
    int *ptrs[5];//= {&a[0],&a[1],&a[2],&a[3],&a[4]};
    sortP(a, ptrs, 5);
}

【讨论】:

    【解决方案2】:

    我的结果是地址

    从技术上讲,您的结果是未定义的行为,因为 %i 需要 int,而不是 int*

    解决这个问题很简单:在ptrs[i]前面添加一个解引用操作符,像这样:

    for(int i = 0; i< n;i++) {
        printf("%i\n", *ptrs[i]);
    }
    

    我得到了奇怪的号码,不是src[]中的号码

    您的代码的真正问题是您错误地交换了指针。实际上,您只需查看 temp 就可以判断它是不正确的:它必须是 int*,而不是 int,并且交换上的取消引用需要消失。

    【讨论】:

    • 我之前尝试过 *ptrs[i],但我得到了奇怪的数字,而不是 src[] 中的数字..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2021-12-08
    相关资源
    最近更新 更多