Thread: array being printed incorrectly

  1. #1
    Registered User
    Join Date
    Dec 2011
    Posts
    3

    array being printed incorrectly

    Hi I'm new to this so be nice . I have written a function to print all the elements of an array. But currently it is printing the wrong values.

    here is part of my code:

    Code:
    void printarray(double *p,int l){
        unsigned short int i;
    
    
        for (i=0; i<l; i++)
        {
            printf("%d\n",*p);
            p++;
        }
    
    
    
    
    }
    
    int main()
    
    
    
    
    {
    
    
        double U,V,positions[6],distances[4],masses[2],F[4],*pdistances,*pF,*ppositions;
        const double G=6.673e-11;
    
        //inputs
        printf("what is the x -co-ordinate of p1 in m\n");
        scanf("%lf",positions[0]);
        printf("what is the y -co-ordinate of p1 in m\n");
        scanf("%lf",positions[1]);
        printf("what is the z -co-ordinate of p1 in m\n");
        scanf("%lf",positions[2]);
    
    
    
    
    
    
        printf("what is the x -co-ordinate of p2 in m\n");
        scanf("%lf",positions[3]);
        printf("what is the y -co-ordinate of p2 in m\n");
        scanf("%lf",positions[4]);
        printf("what is the z -co-ordinate of p2 in m\n");
        scanf("%lf",positions[5]);
       
        ppositions=positions;
        printarray(ppositions,6);
        
        return 0;
    
    }
    I hope you can help thanks.

  2. #2
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    First thing I noticed: if the array is double then the printf format statement needs to have the correct type for that. Not %d.

  3. #3
    Registered User
    Join Date
    Dec 2011
    Posts
    3
    Yeah thanks, I've put in
    Code:
    printf("%lf\n",*p);
    and now it ouputs all zeros which is an improvement.

  4. #4
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    Then you have to supply the addresses to scanf instead of the values in the array.
    scanf("%lf",&positions[0]);

  5. #5
    Registered User
    Join Date
    Dec 2011
    Posts
    3
    Oh yeah thanks, could I also write

    scanf("%f",positions);

    as position[0] is the same as *(positions+0)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer pointing incorrectly
    By edishuman in forum C Programming
    Replies: 3
    Last Post: 11-07-2011, 01:27 AM
  2. Replies: 18
    Last Post: 08-09-2011, 12:55 PM
  3. Replies: 8
    Last Post: 11-12-2008, 11:25 AM
  4. Output Displaying Incorrectly
    By Zildjian in forum C Programming
    Replies: 3
    Last Post: 11-21-2003, 10:59 AM
  5. Declaration terminated incorrectly
    By Griffin2020 in forum C Programming
    Replies: 8
    Last Post: 04-26-2002, 11:53 PM

Tags for this Thread