Help with pointers and arrays

I'm trying to use a pointer to fill an array with the integer 20 and then print the array using the pointer:

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
36
37
38
#include <iostream>

using namespace std;

void table_print(int array, int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << *array << " " << endl;
    }
}

void table_fill(int p, int size, int num)
{
    for (int i = 0; i < size; i++)
    {
        *p = num;
        p++;
    }
}

int main()
{
    const int MAX = 20;
    int *p, *s, *tp;

    int *ary, *bry;
    ary = new int[MAX];
    bry = new int[MAX];
    p = ary;
    s = bry;

    table_fill(p, MAX, 20);
    cout << endl << "Fill array with 20s " << endl;
    table_print(p, MAX); cout << endl << endl;

    return 0;
}


I am getting the error "invalid type argument of unary '*' (have int)". I have no idea what that error means. I am new to pointers and they weren't explained very well in class so I'm not sure that I'm doing this correctly.

I would appreciate any help.
Last edited on
 
void table_print(int array, int size)


Your 'array' value here is of type int. IE: it's a single integer, not a pointer.

You probably meant to do this:
 
void table_print(int* array, int size)


Note the * here makes it a pointer.

Your table_fill function has the same problem.


Also you have a problem here:

1
2
3
4
    for (int i = 0; i < size; i++)
    {
        cout << *array << " " << endl;  // <- you're only printing the 1st element in the array
    }


By printing *array repeatedly, you will just print the first element in the array over and over again. This is not what you wanted to do. Instead, you want to iterate through the array. This can be done 2 ways:

1) increment the pointer after every print.
1
2
cout << *array << " " << endl;
++array;


or

2) Use the subscript [bracket] operator to index the array.
 
cout << array[i] << " " << endl;



Personally I find #2 to be much simpler and more clear.
Thank you, I added the dereference operators in the function arguments / in front of variable array like you suggested and it works now.
Topic archived. No new replies allowed.