-4

I'm trying to play with arrays and pointers by changing everything back and forth from different values, but this code has brought an error 'cannot convert 'int () [4]' to int in initialization, whats wrong here? no declared properly?

#include <iostream>
#include <cctype>
#include <stdio.h>
#include <math.h>

using namespace std;

int main()
{
    int anArray[4] = {1, 2, 3, 4};

    int* firstPnt = &anArray;

    cout << *firstPnt;
}
TheStache
  • 29
  • 1
  • 4
  • You probably meant `int* firstPnt = anArray;` – HelloWorld123456789 Apr 02 '14 at 16:09
  • `&anArray` is of type `int (*)[4]` not `int *`. – alk Apr 02 '14 at 16:10
  • 2
    I think the downvotes are a bit harsh. Justification? – Fred Larson Apr 02 '14 at 16:12
  • 3
    @FredLarson I wish those questions weren't asked here. Everyone rushes here asking why their code doesn't work, and they drown out the real useful questions. I hope those downvotes dissuade at least this guy from coming here **every time his code doesn't compile**. – sashoalm Apr 02 '14 at 16:14
  • yeah wtf is up with the downvoting, that's pretty ignorant – TheStache Apr 02 '14 at 16:31
  • 1
    @TheStache Responding to your (later deleted) comment where you called us "ignorant pricks". I absolutely feel justified downvoting you now, and if you go away, along with your attitude - insulting people you ask questions from, I won't regret it. – sashoalm Apr 02 '14 at 16:51
  • well im sorry but you kind of deserved the remark that was given to you, if you can't handle that I'm sorry but its not my problem – TheStache Apr 02 '14 at 17:08
  • @TheStache: Regardless of the acceptability of any particular words, name calling is not welcome on SO. – Fred Larson Apr 02 '14 at 18:04

3 Answers3

2

An array decays into pointer of the base type when you refer it by name. However, taking the address of it would give a pointer to the array itself. Do either

int (*firstPnt) [4] = &anArray;

or

int *firstPnt = anArray;

The former is a pointer to the whole array, while the latter is a pointer to the first element in the array. When you do ++firstPnt to the latter, it'll move to the next element i.e. sizeof(int) bytes away, while in the former case, it'll move sizeof(int[4]) bytes away i.e. to the byte next to the last byte of the whole array. So if you want to access the elements, you'd do (*firstPnt)[0], (*firstPnt)[1], etc.

Read more about array decay to understand this.

Community
  • 1
  • 1
legends2k
  • 31,634
  • 25
  • 118
  • 222
0

Remove the ampersand.

int* firstPnt = anArray;
sashoalm
  • 75,001
  • 122
  • 434
  • 781
0

You should do

int* firstPnt = &anArray[0];

or

int* firstPnt = anArray;
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174