Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 117,527 C++ Programmers for FREE! Ask your question and get quick answers from experts. There are 1,944 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



Problem with pointer

 
Reply to this topicStart new topic

Problem with pointer

chuck87
post 3 Jul, 2008 - 01:18 PM
Post #1


D.I.C Head

**
Joined: 7 Sep, 2007
Posts: 65


My Contributions


I am trying to dynamically allocate memory for a 2D-array.
The output shows that the array contains only zeros which is my problem.Here is the code

CODE

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

int main(void)
{
   int i,j,n=6;
   double **array;

   array=malloc(n * sizeof(double *));

   for(i=0; i<n; i++)
   {
      array[i]=malloc( n * sizeof(double *));
   }

   for(i=0; i<n; i++){
     for(j=0; j<n; j++){
        array[i][j]=0.2;
        printf("%d\t",array[i][j]);
     }
   }
  
   return 0;
}
User is offlineProfile CardPM

Go to the top of the page


Cerolobo
post 3 Jul, 2008 - 01:26 PM
Post #2


D.I.C Regular

Group Icon
Joined: 5 Apr, 2008
Posts: 440



Thanked 30 times
My Contributions


You've got two issues

Issue Number 1:

CODE
   for(i=0; i<n; i++)
   {
      array[i]=malloc( n * sizeof(double *));
   }


In the above code, you are allocating n * sizeof(double *) bytes. Assuming 32 bit CPU, sizeof(double *) is 4 bytes. What you wanted is sizeof(double), which is 8 bytes, since you are allocating doubles and not double pointers.

Issue Number 2:

CODE
printf("%d\t",array[i][j]);


%d is used to print out integers, not doubles. What you want is %f. %f actually prints out doubles.
User is offlineProfile CardPM

Go to the top of the page

chuck87
post 3 Jul, 2008 - 01:36 PM
Post #3


D.I.C Head

**
Joined: 7 Sep, 2007
Posts: 65


My Contributions


Thanks a lot
User is offlineProfile CardPM

Go to the top of the page

Reply to this topicStart new topic
Time is now: 10/7/08 03:55PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month