1

How do you access/dereference with arrays in c++??

for example, if I have this code

int num[] = {0,1,2,3};
int *p = #

I thought p was point to the first element in num array?

For some reason, I get a compiler error.

I want to use pointers and increments to access and change the value that is pointing,

for example, p gets the address of the first variable in the int array num and if I increment p, I get the address of the second variable in the int array num.

Any tips would be appreciate it.

3
  • 1
    The type of &num is int **. Commented Apr 27, 2016 at 2:38
  • 1
    @kjpus: actually, the type of &num is int (*) [4]. The sizeof and & operators have special meaning for array types. Commented Apr 27, 2016 at 2:51
  • 1
    @dreamlax actually they have the same meaning for all types; it is the array types which have special meaning in other contexts Commented Apr 27, 2016 at 2:52

1 Answer 1

8

I thought p was point to the first element in num array?

No. int *p = # is wrong, since &num is not a pointer to an int, i.e. int*, but is actually a pointer to an array of ints, i.e. int (*) [4].

To get a pointer to the first element, you can use int *p = num;, or int *p = &num[0]; instead.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.