pointer to array to function

Hey guys,

So I have to write a code that uses a pointer for call by reference to send the elements of an array to a function one at a time. The function should find the sum of the elements of the array.

I keep running into errors. Can somebody help me out please. Thanks


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34


 // Example program
#include <iostream>
using namespace std;


int sum (int*x);


int main()
{
    
    int gradeArray [10]={1,2,3,4,5,6,7,8,9,0};
    
    int *q= gradeArray[0];
    
    cout << "\nThe sum is " << sum (*q);

}

int sum (int *x)
{
    int totalSum= 0;
    for (int i =0; i < 10; i++)
    {
        
        *x[i]=+ totalSum;
        return totalSum;
        }
    
}

 
Last edited on
Hi,

Could we ask you to in the future post the compiler errors that you have. It's fairly obvious in this example, but it is easier on everyone if you show the compiler output - then we can explain the errors to you.

Some questions to make you think about what is happening here.

What is the value of *q on line 18 ? Try it by printing it out with std::cout on line 17.

On line 28 there the same problem as on line 18. Also, What value are you trying to assign to you array? Why are you assigning to your array?

What happens on line 29? What is the value of i at this point?

Some other things:

Avoid having magic numbers in your code, make them const variables instead, and use that variable name in your code :

const unsigned short ArraySize = 10; // technically std::size_t is better

1
2
3
4
for (int i =0; i < ArraySize; i++)
{
   // your code
}  // make sure braces line up - it's visual thing so one can spot where the end of the loop body is 


When using a brace initialiser list, the compile can count the number of values in the array, so you don't need to specify that.

int gradeArray[] = {1,2,3,4,5,6,7,8,9,0};

The name of an array degrades to a pointer, so no need to specify a subscript if you want to.

int* q = gradeArray;

Avoid line 5, read up on Google to see why. The easiest thing to do, is to put std:: before each std thing. This seems a pain, and there are other ways to achieve the same thing, but this is the easiest way in the end, and all the expert coders on this site all do it that way.

Hope this helps :+)

Edit:

It is the the += operator , not =+
Last edited on
Sorry for not being clear in the original post. I'm trying to get a pointer as a parameter of the function. The pointer will then pass each element of the array to the function, which will take the sum of the array.

The first code was my vague attempts at it. As I was writing it-- it seemed wrong.

I'm still working on it- but here's an update. still doesn't work thought. But am i getting closer??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;


void sum (int *x)
{
    int totalSum=0;
    for (int i =0; i< 10; i++)
    {
        totalSum=+ *x[i];    
        
    }
    cout << "\n" << totalSum;
    }



int main(){
    const int size= 10;
    int array [size]= {1,2,3,4,5,6,7,8,9,0};
    
 
    
    cout << "\nThe sum is " <<sum (&array) << endl;


	system ("pause");
	return 0;
}








the compiler is saying that

In function 'void sum(int*)':
11:24: error: invalid type argument of unary '*' (have 'int')
In function 'int main()':
25:42: error: cannot convert 'int (*)[10]' to 'int*' for argument '1' to 'void sum(int*)'
Last edited on
Hi,

I think you need to review what the roles of * and & are with respect to pointers.

The * has two roles, the first is to declare a pointer type int* x; The second is to dereference (get the value the pointer points to)

The & produces the address of a variable (a pointer)

1
2
3
4
int x = 10;

int* PointerToX = &x;
int XValue = *PointerToX; // should be 10 


So for your code, look at lines mentioned in the error message, take into account what I have said about * and & Also, what I said about the array name being a pointer to the array already.

I liked your first version of the code better, now you have other problems with the second version. Declaring the function before main is good practice, and it still needs to return an int. Can you tell me why?

I should have said earlier, that the size variable needs to be passed to function so you can use it there.

What level of compiler warnings do you have? There is still a problem with the =+ it should be +=
Set your warning to it's highest, on g++ or clang I use -Wall -Wextra -pedantic. On VS it's a problem because level 4, spits out untold warnings about the include files.
ALso,

x[i] is the i'th element of x , so dereferencing it doesn't make sense.

You can do pointer arithmetic though. *(x +i) is the same as array[i] if x is a pointer to array.

The array variable name might cause problems, because of line 2. std::array exists in the STL. This is why it's not good to have line 2 - it causes naming conflicts - which is what namespaces are supposed to avoid !!
Okay. I think i'm getting somewhere.
The confusing bit was about the array name being a pointer to the array.
So if my parameter for fn sum is (int *x), then when I call it in main, I can just write sum (arrayName) Right?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;


int sum (int *x)
{
    int totalSum= 0;
    for (int i =0; i < 10; i++)
    {
        
        totalSum += *(x+1);
        return totalSum;
        }
    
}


int main()
{
    const int size = 10;
    int gradeArray [size]= {1,2,3,4,5,6,7,8,9,0};
    

    
    cout << "\nThe sum is " << sum (gradeArray);

}




which is what i've done above. Now the code runs, but my sum is 2.
I'm trying to trace back the code but.... not having much luck.
Oh. I see. What the compiler is doing is adding 1 to the array[0]=1, therefore giving me 2.
and it puts that in totalSum.
But I put the for loop there so that it can run through all the array elements and sum them up.

What part am I messing up? Also thanks man-- you're really helpful at explaining things.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
// using namespace std; // *** avoid: just use std::cout etc.

int sum( const int* x, int n ) // *** const, n is the number of elements
                               //     (avoid  hard-coded magic numbers)
{
    int totalSum = 0;

    for( int i = 0 ; i < n /*10*/ ; /*i++*/ ++i ) // *** favour prefix++ over postfix++
                                // it doesn't matter in this case; but it is a good habit to acquire
    {
        // totalSum += *(x+1);
        totalSum += x[i] ; // **** add the value of the element at position 'i'

        // return totalSum; // *** don't return a partial sum (sum before the loop is completed)
    }

    return totalSum ; // value of sum after the loop has finished
}


int main()
{
    const int size = 10;
    int gradeArray [size]= {1,2,3,4,5,6,7,8,9,0};

    std::cout << "\nThe sum is " << sum( gradeArray, size ) << '\n' ; // **** good to have a newline at the end
}
update- success is exceedingly sweet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

#include <iostream>
using namespace std;


int sum (int *x)
{
    int totalSum= 0;
    for (int i =0; i < 10; i++)
    {
        
        totalSum += *(x+ i);
        
        }
    return totalSum;
}


int main()
{
    const int size = 10;
    int gradeArray [size]= {1,2,3,4,5,6,7,8,9,0};
    

    
    cout << "\nThe sum is " << sum (gradeArray);

}



so the above gets me my sum of 45. I kinda tried everything before I randomly attempted that. I'm still sort of confused as to what sort of sorcery I just pulled off.

It went along with what you were talking about-- pointer arithmetics.

If it isn't annoying could you please explain how that code worked.

Thanks
Hi,

You should note and implement the things that JLBorges has mentioned :+)

There is more than one of doing things, note that one has to be careful with pointer arithmetic - it is easily error prone. And if you are learning C++ (as opposed to C) then there is much less use of raw pointers because there are plenty of other much better ways of doing things, like STL containers std::vector etc

So with the pointer arithmetic, x[i] and *(x + i) are equivalent.

Pointer arithmetic is used to create some very concise code as shown below.
Here is an excerpt from K&R C programming.

1
2
3
4
5
6
7
/* strcpy: copy t to s; pointer version 3 */
void strcpy(char *s, char *t)
{
  while (*s++ = *t++) {
       ;   /* null statement*/
  }
}


I added extra parenthesis and the comment.

If you are interested in C programming, here is the original book by the inventors of the language. Be careful though, there are modern good practice like the braces and comment above that aren't shown in the book. Also be very aware that C language is a very different animal to C++

http://zanasi.chem.unisa.it/download/C.pdf
Topic archived. No new replies allowed.