我必须编写一个程序,该程序编写一个使用堆存储数组的程序。我有一个问题,该程序将在成功运行后崩溃。我还有一些小的美学问题,该元素需要从1开始并且在最后打印的数字上没有逗号。有人可以帮忙吗?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int size = 0;
int* num_elements;
num_elements = (int*)malloc(sizeof(int) * 3);
printf("How many int elements will you enter?");
scanf("%d", &size);
printf("\n");
for (int k = 0; k < size; k++)
{
printf("Element %d: ", k);
scanf("%d", &num_elements[k]);
}
printf("\n");
printf("The Array stores the following values: \n\n");
for (int j = 0; j < size; j++)
{
printf("%d, ", num_elements[j]);
}
printf("\n");
free(num_elements);
num_elements = 0;
return 0;
}
如果用户输入的值大于3,则最终将使用超出范围的内存。使用动态内存分配时,请充分利用它。问的价值size
从用户,然后用它来调用malloc()
像
int* num_elements;
printf("How many int elements will you enter?");
scanf("%d", &size);
num_elements = malloc(size * sizeof *num_elements);
然后,要从中打印元素编号1
,您可以像这样写
printf("Element %d: ", k+1);
那就是
malloc()
和的返回值转换为的讨论C
。。malloc()
使用前,请务必检查成功的返回值。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句