Sharjil.lodhi
Sharjil.lodhi

Reputation: 11

Unable to print the array values in C

It's just a simple C program to display the array elements taken from the user but idk why am getting the garbage values when trying to print the array... if anyone could help i would really appreciate that... thanks!!

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

double *array_dou;

double* initializeDoubles(int *maxdouble)
{

printf("Enter the max. double value the program should support: ");
scanf("%d",maxdouble);
array_dou = (double *) malloc((*maxdouble)*sizeof(double));
if(array_dou == NULL)                     
{
    printf("Error! memory not allocated.");
    exit(-1);
}

return array_dou;
}

int enterDouble(double *doubles,int dcount,int maxdouble)
{
 for(dcount=0; dcount<maxdouble; dcount++)
 {
printf("Please enter a double value: ");
scanf("%f",&doubles[dcount]);
 }
return dcount;
}

int main()
{
int maxdouble;

int dcount=0;

double *doubles;

doubles = initializeDoubles(&maxdouble);

dcount = enterDouble(doubles,dcount,maxdouble);

printf("\nDouble array\n");

for(int j=0;j<dcount;j++)
{
printf("%lf  ",doubles[j]);
}
return 0;
}

Upvotes: 0

Views: 49

Answers (1)

Pablo
Pablo

Reputation: 13580

Because you are calling enterDouble only once and it reads only one value. Besides you are accessing the memory out of bounds. You allocated dcount number of elements, so you can access the memory only through the indices 0 to dcount - 1, yet you are passing dcount to enterDouble, thus you are trying to write at index dcount (one past the limit).

All other entries are uninitialized, so there you have two reasons why you see "garbage": the undefined behaviour of accessing memory out of bounds and the fact that you haven't initialized any of the doubles.

What you need to do is call enterDouble for all indices:

for(int j = 0; j < dcount; ++i)
    enterDouble(doubles, j);

And the dcount++; in enterDouble makes to me no sense, the caller knows which index it it passing, no need to returns the same index + 1.

Also see do not cast malloc and you are not freeing the memory you've allocated.

Also the proper conversion specifier for reading doubles with scanf is %lf, not %f.

man scanf

...

l Indicates either that the conversion will be one of d, i, o, u, x, X, or n and the next pointer is a pointer to a long int or unsigned long in (rather than int), or that the conversion will be one of e, f, or g and the next pointer is a pointer to double (rather than float).

...

f Matches an optionally signed floating-point number; the next pointer must be a pointer to float.

Upvotes: 1

Related Questions