Sums of an array ??

This is a discussion on Sums of an array ?? within the C Programming forums, part of the General Programming Boards category; I typed this program Code: #include <stdio.h> #define SIZE 10 int sum(int ar[], int n); int main(void) { int marbles[SIZE] ...

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    7

    Sums of an array ??

    I typed this program

    Code:
    #include <stdio.h>
    #define SIZE 10
    
    int sum(int ar[], int n);
    int main(void)
    {
      int marbles[SIZE] = {20,10,5,39,4,16,19,26,31,20};
      long answer;
      answer = sum(marbles, SIZE);
      printf ("The total number of marbles is %ld.\n", answer);
      printf ("The size of marbles is %d bytes.\n", sizeof (marbles));
      return 0;
    }
    
    int sum(int ar[], int n)
    {
    int i;
    int total = 0;
    for (i = 0; i < n; i++)
    	total += ar[i];
    printf("The size of ar is %d bytes.\n", sizeof (ar));
    return total; 
    }
    I am supose to get:
    ar size of 4 bytes
    total marbles of 190
    marbles size of 40 bytes


    what I get is:
    ar size of 2 bytes
    total marbles of 190
    marbles size of 20 bytes


    what am I doing wrong? I am really jsut trying to pass the value of an array from 1 function to the next for my assigment...
    Last edited by RedRattler; 04-04-2003 at 06:32 PM.

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,630
    Nothing!

    You're using a 16bit compiler, meaning sizeof(int) == 2 and sizeof(int*) == 2.

    There is no point in declaring "answer" as a long since sum() returns an int.

    gg

  3. #3
    Registered User
    Join Date
    Mar 2003
    Posts
    7
    ahhh. Thanks for reminding me of the obviouse...

    greatly appreciated

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. from 2D array to 1D array
    By cfdprogrammer in forum C Programming
    Replies: 17
    Last Post: 03-24-2009, 10:33 AM
  3. Replies: 6
    Last Post: 11-09-2006, 02:28 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21