gpt4 book ai didi

c - C 中用户定义的数组程序出现问题

转载 作者:行者123 更新时间:2023-11-30 19:12:15 25 4
gpt4 key购买 nike

我必须编写一个程序,编写一个使用堆来存储数组的程序。我有一个问题,程序在成功运行后会崩溃。我还有一些小的审美问题,元素需要从 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);

也就是说,

  1. Please see this discussion on why not to cast the return value of malloc() and family in C. .
  2. 使用前务必检查 malloc() 的返回值是否成功。

关于c - C 中用户定义的数组程序出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37525850/

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