-1

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. 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;
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 2
    @PinkPanther11222: He told you wrong then. Initialisation is done with the definition (note it includes "initial"). Anything else is not an initialisation, but an assignment. (it is good practice for beginners on PC, though) – too honest for this site May 30 '16 at 12:47
  • @Olaf Thank you, I will remember that for future reference – PinkPanther11222 May 30 '16 at 12:52
  • Do you really have to write a program that writes a program (i.e. a code generator) -- or is it enough to just write a program? – John Coleman May 30 '16 at 12:55

1 Answers1

1

In case user enters a value more than 3, you'll end up using out of bound memory. 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

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

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..
  2. Always check the return value of malloc() for success before using.
Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261