Heap + gets + puts!!! Need help

+2 K B · January 25, 2015
// Please help me out. If I replace 'element' with a constant say 10, this works perfectly. But when I take the value of element //from the user, this code gives issues. What could be the reason?? 


#include <stdio.h>
#include <stdlib.h>

int main()

{

    int element;
    char * chararray;


    printf("Enter the number of elements that you would like to enter. \n");
    scanf(" %d", &element);

    chararray = (char *) malloc(element * sizeof(char));

    puts("Enter the elements in your array");

    gets(chararray);


    puts(chararray);


    return 0;
}

Post a Reply

Replies

Oldest  Newest  Rating
+1 Lazar Bulic · January 25, 2015
Scanf is tricky and sometimes it leaves some strange values in the buffer.
After scanf add this and it will do the trick. 



fflush(stdin);


Also always FREE space at the end of program! 



free(chararray);
  • 1

C

124,357 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator