在C中分配动态内存的问题

时间:2015-03-21 15:01:55

标签: c

我正在尝试为数组中的多个整数分配动态内存,然后用随机数填充数组。问题是,如果我为5个元素执行此操作,它可以工作......如果我这样做了,它就会崩溃,我不知道为什么。这是我的代码:

int main()
{
   int i;
    int* arr=generateRandomInts(50);
    printf("Given array:\n");
    show(arr,50);
    return 0;
}

int* generateRandomInts(int n)
{
    int i; int *v;
    v=(int*)malloc(n*sizeof(int));
    srand(time(NULL));
    for(i=1;i<=n;i++)
    {
        v[i]=rand()%200;
    }
    return v;
}

void show(int *v,int n)
{
    int i;
    for(i=1;i<=n;i++)
    {
        printf("%d ",v[i]);
    }
}

1 个答案:

答案 0 :(得分:0)

你不需要分配n + 1个职位(这太可怕了:P)

这里有一个我在互联网上找到的使用堆排序算法对你有用的例子。

/*
 * C Program to sort an array based on heap sort algorithm(MAX heap)
 */ 
#include <stdio.h>

int main()
{
    int heap[10], no, i, j, c, root, temp;

    printf("\n Enter no of elements :");
    scanf("%d", &no);
    printf("\n Enter the nos : ");
    for (i = 0; i < no; i++)
       scanf("%d", &heap[i]);
    for (i = 1; i < no; i++)
    {
        c = i;
        do
        {
            root = (c - 1) / 2;             
            if (heap[root] < heap[c])   /* to create MAX heap array */
            {
                temp = heap[root];
                heap[root] = heap[c];
                heap[c] = temp;
            }
            c = root;
        } while (c != 0);
    }

    printf("Heap array : ");
    for (i = 0; i < no; i++)
        printf("%d\t ", heap[i]);
    for (j = no - 1; j >= 0; j--)
    {
        temp = heap[0];
        heap[0] = heap[j];    /* swap max element with rightmost leaf element */
        heap[j] = temp;
        root = 0;
        do 
        {
            c = 2 * root + 1;    /* left node of root element */
            if ((heap[c] < heap[c + 1]) && c < j-1)
                c++;
            if (heap[root]<heap[c] && c<j)    /* again rearrange to max heap array */
            {
                temp = heap[root];
                heap[root] = heap[c];
                heap[c] = temp;
            }
            root = c;
        } while (c < j);
    } 
    printf("\n The sorted array is : ");
    for (i = 0; i < no; i++)
       printf("\t %d", heap[i]);
    printf("\n Complexity : \n Best case = Avg case = Worst case = O(n logn)\n");

    return 0;
}

来源:http://www.sanfoundry.com/c-program-heap-sort-algorithm/

希望这有帮助。