【问题标题】:Incorrect size of array数组大小不正确
【发布时间】:2012-03-18 00:52:57
【问题描述】:
#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;
}

http://codepad.org/zcfNOtye

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

【问题讨论】:

标签: c arrays argument-passing heapsort


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 2014-10-06
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多