简体   繁体   English

C 语言中的用户定义数组程序有问题

[英]Having issues with a user defined arrays program in C

I have to write a program that writes a program that uses the heap to store an array.我必须编写一个程序来编写一个使用堆存储数组的程序。 I have a problem where the program will crash after successfully running it.我有一个问题,程序在成功运行后会崩溃。 I also have some small aesthetic problems, the element needs to start at 1 and no comma on the last number that is printed.我也有一些小的美学问题,元素需要从 1 开始,并且在打印的最后一个数字上没有逗号。 Can anyone help?任何人都可以帮忙吗?

#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;
}

In case user enters a value more than 3, you'll end up using out of bound memory.如果用户输入的值超过 3,您最终将使用超出范围的内存。 As you're using dynamic memory allocation, make the best of it.当您使用动态内存分配时,请充分利用它。 Ask the value of size from the user and then, use it to call malloc() like从用户那里询问size的值,然后用它来调用malloc()就像

int* num_elements;

printf("How many int elements will you enter?");
scanf("%d", &size);

num_elements = malloc(size * sizeof *num_elements);

Then, to print the element numbering from 1 , you can write it like然后,要打印从1编号的元素,您可以这样写

printf("Element %d: ", k+1);

That said,那说,

  1. Please see this discussion on why not to cast the return value of malloc() and family in C .请参阅有关为什么不在Cmalloc()和 family 的返回值的讨论。 . .
  2. Always check the return value of malloc() for success before using.使用前务必检查malloc()的返回值是否成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM