-1

hi i have this function

int printofarray(int *j,double *n)
{
int x,k;
k=*j;
if(n==NULL) {
printf("array was not created\n");
return 1;}

for(x=0;x<k;x++){
printf("%.2lf\n",*(n+x));}

return 0;
}

when i use it the output is like this

34.77
6114.05
410.70

but i want to write them this way

  34.77
6114.05
 410.70

idea how?

M.Puk
  • 762
  • 9
  • 25
  • Whitespaces and English, please! Also, don't cast the return value of `malloc()`. –  Nov 17 '12 at 16:11
  • 1
    @userXXX [It's wrong that you're using 3 question marks.](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) –  Nov 17 '12 at 16:22
  • 1
    @userXXX read the question & answer? **It is.** –  Nov 17 '12 at 16:25
  • we are using it from beggining and its working – M.Puk Nov 17 '12 at 16:29
  • @userXXX it might work in certain cases, but [this segfault](http://stackoverflow.com/questions/7545365/why-does-this-code-segfault-on-64-bit-architecture-but-work-fine-on-32-bit) was caused by casting the return value of `malloc()`. –  Nov 17 '12 at 16:45

2 Answers2

2

You are dynamically allocating the array dni as:

dni=(int *) malloc(number*sizeof(int)); 

not assigning any values its element but at the end printing the elements, which will obviously print garbage.

codaddict
  • 445,704
  • 82
  • 492
  • 529
  • You pick a couple different ways to dereference your pointers. Not saying that this is wrong, but that consistency may help with debugging. In any case, use printf statements liberally to find out what values you are assigning to your variables. – Alex Reynolds Nov 17 '12 at 16:12
0

Your print statement is left aligning. If you want the decimal lined up, you have to have an idea as to what size of number you are dealing with. The easiest way would be to specify the number of digits, like this. Of course, this would break if you had 5 places instead of 6.

for(x=0;x<k;x++){
printf("%7.2lf\n",*(n+x));}
PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142