pointer to array of integers

I was looking for pointer to an array of integers. I know that int * means pointer to integer type. On same lines, I thought int *[6] means pointer to array of integers. It looks like some online posts are saying int (*)[6] is the correct one? Can someone please tell me which is correct? Why should we put the pointer in parentheses(*)? Does it work without the parentheses?
Last edited on
Does it work without the parentheses?

LIke this you mean?

int *[6] ptr = &some_array;

Have you tried to compile it?? Why not try it and see.

I was looking for pointer to an array of integers.

Is this just to learn about them, or is there a particular problem you want to solve with one?

Andy

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;

// control what initialization and display code is compiled
#define INIT  1
#define DISP  1

int main() {
    int some_array[6] = {1, 2, 3, 4, 5, 6};

#if INIT == 1
    int *[6] ptr = &some_array; // does this work?
#elif INIT == 2
    int *ptr[6] = &some_array;  // you prob already know what's up here?
#else
    int (*ptr)[6] = &some_array;
#endif

    for(int i = 0; i < 6; ++i) {
#if DISP == 1
        std::cout << *ptr[i] << "\n";
#else
        std::cout << (*ptr)[i] << "\n";
#endif
    }

    return 0;
}
Last edited on
thanks @andywestken for that wonderful explanation.

I tried your code online and figured only int (*ptr)[6] works. INIT 1 & INIT 2 did not work, both didn't compile. In display, DISP 1 displays address, else displays the values.

I did not understand the reasoning behind it though. Why is brace-enclosed initializer needed here?

I came across this question while working on hash map implementation. This is not for an assignment :)
Why is brace-enclosed initializer needed here?

Do you mean, why doesn't int *ptr[6] work?

Because the compiler has already taken the * following the int to deduce that you want a pointer-to-int type (int *), so ptr ends up being an array of this type (these pointers.)

The brackets stop the compiler from associating the * with the int, forcing it to associate it with the variable (array).

Basically, it's because that's the way the C++ compiler understands C++ syntax!

I fall into the "type-ist" camp (cf. syntax-ist) and write this as:

int* ptr[6];

(See Is ``int* p;'' right or is ``int *p;'' right? section here:
http://www.stroustrup.com/bs_faq2.html )

Andy
Last edited on
Wow @andywestken, thanks for that explanation. You added lot more clarity to the concept with that explanation. I think I am much more comfortable with this syntax now, thanks to you :)
Topic archived. No new replies allowed.