2016-05-30 60 views
-1

我必须编写一个程序来编写一个使用堆来存储数组的程序。在成功运行程序后,我遇到了一个问题。我也有一些小的美学问题,元素需要从1开始,最后打印的数字上没有逗号。谁能帮忙?在用户定义的数组程序中遇到问题C

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

@ PinkPanther11222:他告诉过你了。初始化与定义一起完成(注意它包括“初始”)。其他任何事情都不是初始化,而是一项任务。 (这对PC初学者来说是个好习惯),但是) – Olaf

+0

@Olaf谢谢,我会记住,以供将来参考 – PinkPanther11222

+0

您是否真的必须编写一个程序来编写程序(即代码生成器) - 或者它是否足够只写一个程序? –

回答

1

如果用户输入的值超过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()是否成功。
+0

谢谢你的回应。我的代码现在正在工作。我对C相当陌生,所以我会看看这个讨论。 – PinkPanther11222

+0

是的,和downvote背后的原因? –

相关问题