0

I am working on what I thought would be a simple program to try and familiarize myself with C style code (vs. the C++ I'm used to), and have hit a roadblock.

I have allocated memory for an array using calloc, and want the user to simply enter a number, and have that number put into the array (this repeats until the array is fully populated). The array seems to have been created, but my code is not writing to the array. The program, when run, accepts an input, stores that input to a temporary variable,q (used for debugging purposes), but will not write the value of that temporary variable to the array.

Here is a snippet of code that I believe holds my issue:

//e is the size of array as indicated by user
values = (double *)calloc(e , sizeof(double));
double q = 0; // holds input just to make sure it works
for (int i = 0; i < e; i++)
{
    printf("Please enter value %d: ",i+1);
    scanf("%d", &q);
    printf("%d", q); // confirms q = "input"
    values[i] = q; //This isn't happening for me
} 

I would really appreciate it if someone could please correct (and ideally explain) my error as to why values[i] is never equal to q.

Ayush
  • 3,989
  • 1
  • 26
  • 34
  • 1
    ***[Do not cast the return value of memory allocator functions!](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858)*** –  Jul 14 '13 at 05:49

1 Answers1

2

The %d format specifier is for ints. For doubles use %lf with scanf and %f or %lf with printf.

scanf("%lf", &q);
printf("%f", q); // confirms q = "input"
Community
  • 1
  • 1
John Kugelman
  • 349,597
  • 67
  • 533
  • 578