[英]Arrays of pointer dereferencing
我想要一個名為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函數中,我將此函數稱為
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()中進行哪些更改?
謝謝
PS我以前嘗試過* ptrs [i],但是我得到了一個奇怪的數字,而不是src []中的數字。
我的結果是地址
從技術上講,您的結果是未定義的行為,因為%i
期望一個int
,而不是int*
。
解決這個問題很簡單:在ptrs[i]
前面添加一個解引用運算符,如下所示:
for(int i = 0; i< n;i++) {
printf("%i\n", *ptrs[i]);
}
我得到的是一個奇怪的數字,而不是
src[]
的那個
代碼的真正問題在於您錯誤地交換了指針。 實際上,僅通過查看temp
就可以判斷出它是不正確的:它需要是int*
,而不是int
並且需要取消掉對swap的取消引用。
查看注釋:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.