Rampager
Rampager

Reputation: 13

C how to make function that returns sum and product of array using pointers? assignment makes integer from pointer

I am attempting to make a function that is able to calculate the sum and product of an array and return both values using pointers Right now I have

    #include <stdio.h>

    void SandM(int a[], int size, int* Sump, int* Mulp);

    int main(void)
{
    int size = 5;
    int a[size];
    int i;
    int s;
    int m;
    printf("Enter the elements of the array\n");
    for (i = 0; i < size; i++)
   {
    scanf("%d", &a[i]);
   }

   SandM(a, size, &s, &m);

   printf("sum = %d\n", s);
   printf("product = %d\n", m);

   return 0;
}

void SandM(int a[], int size, int* Sump, int* Mulp)
{
   int inSum = 0;
   int inMul = 1;
   int j;
   Sump = &inSum;
   Mulp = &inMul;

  for(j=0;j<size;j++)
  {
    *Sump += &a[j];
    *Mulp *= &a[j];
  }

}

Now the errors im getting is warning: assignment makes integer from pointer without a cast [Enabled by default] *Sump += &a[j]; and error: invalid operands to binary * (have 'int' and 'int *') *Mulp *= &a[j];

What i am trying to do is first create variables to initialise the sum pointer (sump) to 0 and the multiplication pointer (mulp) to 1 then get the value of sump and add that to the value of the jth address of the array and similar to mulp. Why does this not work?

Upvotes: 0

Views: 2225

Answers (2)

Woody Huang
Woody Huang

Reputation: 484

You need to have a better understandings about pointers. The function SandM should implemented as:

void SandM(int a[], int size, int* Sump, int* Mulp)
{ 
  *Sump = 0;
  *Mulp = 1;
  for(j=0;j<size;j++)
  {
    *Sump += a[j];
    *Mulp *= a[j];
  }

}

I planned to give some detail explanation, but since the concept is so basic, I recommend that you go to get a textbook about C.

Upvotes: 3

Dominic Gibson
Dominic Gibson

Reputation: 67

You are following the pointer Sump and Mulp and add or multiply the Adresses of a. Just get rid of the &.

for(j=0;j<size;j++)
{
  *Sump += a[j];
  *Mulp *= a[j];
}

Upvotes: 0

Related Questions