数组大小不正确

编程入门 行业动态 更新时间:2024-10-25 19:32:18
本文介绍了数组大小不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 #include <stdio.h> void Heapify(int num[], int start, int end) { int root = start; while(root*2+1<=end) { // at least one child exists int swap = root; int lchild = root*2+1; int rchild = root*2+2; if(num[swap]<num[lchild]){ swap = lchild; } if(rchild<=end && num[swap]<num[rchild]){ swap = rchild; } if(swap!=root){ // swap here int temp = num[root]; num[root] = num[swap]; num[swap] = temp; root = swap; } else return; } } void buildHeap(int num[]) { int length=sizeof(num)/sizeof(num[0]); int start = (length/2)-1; // Starting from last parent int end = length-1; while(start>=0){ Heapify(num,start, end); if(start==0) break; start= start-1; } } void heapsort(int num[]) { int length=sizeof(num)/sizeof(num[0]); printf("length = %d ", length); // length = 1 (Wrong) buildHeap(num); int i; //for (i = 0; i < length; i++) //printf("%d ",num[i]); int end = length-1; while(end>0){ // swap first elem with last int temp = num[0]; num[0] = num[end]; num[end] = temp; Heapify(num,0,end-1); end--; } } int main() { int num[]={1,7,-32,4,101,-99,16,3}; heapsort(num); return 0; }

codepad/zcfNOtye

当我在main中打印它时,长度显示正确但在函数内部(堆排序),则显示错误。我在传递数组时找不到任何错误。我缺少什么?

When I print it in main, the length is showing correct but inside the function(heap sort), its showing wrong. I can't find any mistakes in passing the array. What am I missing?

推荐答案

数组作为参数传递给指针时会衰减,您需要将数组的长度作为

Arrays decay to pointers when passed as parameters, you need to pass the length of the array as a separate parameter.

即:找不到这样的数组长度。

I.e.: you can't find the length of the array like this.

void buildHeap(int num[]) { int length=sizeof(num)/sizeof(num[0]); }

sizeof(num)将返回 sizeof(int *)。

更多推荐

数组大小不正确

本文发布于:2023-11-10 06:09:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574563.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   不正确   大小

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!