【发布时间】: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 "它有错误" -- 如果您遇到错误,请提及确切的错误。这个错误很有帮助。