gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:10:36 25 4
gpt4 key购买 nike

我试图为数组中的多个整数分配动态内存,然后用随机数填充数组。问题是,如果我这样做 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]);
}
}

最佳答案

你不需要分配 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/

希望这有帮助。

关于c - 在 C 中分配动态内存的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29184185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com