2

I'm new to C++ and I cannot figure out how pointers work in relation to arrays. I do cannot figure out how I am supposed to access an element in an array pointer. Here's what I mean:

int* array[10];

(*array)[5] = 4;// This works but I don't think that that is the correct way to do it
array->[5] = 4; // Is there a similar method such as what you would use for a normal pointer?

Also I was wondering if you could initialize an array pointer like you can initialize a regular array with an array in curly brackets.

int  array[] =  {0, 2, 45, 235};// Works
int* array[] =  {0, 2, 45, 235};// does not work
int* array[] = &{0, 2, 45, 235};// does not work

EDIT: Some of you are suggesting to use an array without a pointer. But if i do this, wont it make a copy whenever i pass it into a method like with normal variables?

Stas Jaro
  • 4,747
  • 5
  • 31
  • 53
  • 1
    If you're "new to C++", the *last* thing you should be doing is filling your brain with useless garbage about pointers and arrays. Seriously. There's still time for that after you learned how to write real C++ code. – Kerrek SB Dec 05 '11 at 20:54
  • @Kerrek SB Well I'm fluent in 5 other computer languages so I already know the basics of coding. – Stas Jaro Dec 05 '11 at 20:57
  • @stas: I think Kerrek's point is that in real C++ code you probably shouldn't be using pointers and arrays to begin with. – John Dibling Dec 05 '11 at 21:02
  • Why would you not use arrays!? Do you only use ? – Stas Jaro Dec 05 '11 at 21:03
  • 1
    @stas: Mostly. But also sometimes `std::array`, `std::deque` and `std::list`. – Benjamin Lindley Dec 05 '11 at 21:13
  • @stas: In real production code, yes, I use `` and try to avoid using regular C-style arrays. The reasons for `vector` are many and the resons forC-type arrays are few. I can't possibly go in to them all here. Consider just three reasons for now: 1) Arrays mean either `new` or fixed-size arrays. Fixed-size arrays are rarely useful in the real world. 2) Every time you use `new`, you expose yourself to memory leaks and pointer-ownership bugs. 3) Many implementations of `vector` give you debugging tools to catch out-of-bounds and other bugs in your code. Arrays don't. – John Dibling Dec 05 '11 at 21:18
  • ... and `string`s and `unique_ptr`s and `tuple`s and `template`s and variadics... there's a ton of *relevant* C++ that's far more worthwhile learning that C-style arrays and naked pointers. Raw pointers really only serve two purposes: low-level memory management, and I/O (so you only need `void*` and `char*`). Raw arrays serve none. – Kerrek SB Dec 05 '11 at 21:22
  • @Kerrek: I would not go so far as to say that arrays serve absolutely no purpose, but I completely agree with your sentiment. – John Dibling Dec 05 '11 at 21:25
  • @JohnDibling: I use fixed-size arrays all the time in java and they are very useful. I see why you would use a vector instead in c++ though. – Stas Jaro Dec 05 '11 at 21:26
  • @KerrekSB: One more purpose for raw pointers: Non-owning re-assignable references to non-dynamically allocated objects. The only purpose as far as I'm concerned for someone not writing the standard library. – Benjamin Lindley Dec 05 '11 at 21:28
  • 1
    @stas: I would be willing to bet that for almost every valid use case you can name in Java for a fixed-size array, I can point out why there is a better alternative in C++. – John Dibling Dec 05 '11 at 21:28
  • @stas: I don't know enough about Java to speak on that side of the argument, though. – John Dibling Dec 05 '11 at 21:29
  • @JohnDibling: In java, are really slow :P. You have to use arrays when you require speed. – Stas Jaro Dec 05 '11 at 21:34
  • @stas: In C++, `vector` is not "really slow," but naieve use of it can be -- but the same is true of anything else. – John Dibling Dec 05 '11 at 21:35
  • @JohnDibling: I don't mean it's "REALLY SLOW" its just that if you are writing say a physics engine which requires storing a lot of data in an array-like format, i can get double the fps when using an array instead of a – Stas Jaro Dec 05 '11 at 21:38
  • [related FAQ](http://stackoverflow.com/questions/4810664/) – fredoverflow Dec 06 '11 at 05:35

10 Answers10

4
int * array[10]

That's not an array pointer. It's an array of pointers. You put pointers in it, not integers.

An array pointer would look like this:

int (*ptr)[10] = &array;

But that also is not filled with integers. It is filled with arrays of 10 integers. More accurately, it points either to a single array of 10 integers, or to the first array in an array of arrays of 10 integers.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
1

This declaration:

int* array[10];

...might not be what you think it is. This is a declaration of an array of 10 pointers-to-int. It's not an array of 10 ints.

Since you haven't actually initialized each of those 10 pointers, trying to access one of them evoked Undefined Behavior. That's what you're doing here:

(*array)[5] = 4;

...and again here:

array->[5] = 4;

What you probably want is an array of 10 ints, which you declare like this:

int array[10];

Now you can access the items just like this:

array[5] = 4;

But, while we're on the subject of arrays, why not use a vector instead and avoid all this mess?

vector<int> vi;
vi.push_back(1);
/* ... */
John Dibling
  • 99,718
  • 31
  • 186
  • 324
0

For an array of plain datatypes like int the -> operator is not definied. The * operator is the dereferencing operator, giving you the element where every pointer points to. In your case to an int*.

For the second part of your question, only method one is valid to initalize an array with constant data.

Michael Haidl
  • 5,384
  • 25
  • 43
0

For number one, because array is an array of 10 int*s which point to some random memory location, you need to make the pointers point to an int (this should also answer your next question):

// 10 ints on the heap held in an array on the stack
int* array[] = {new int, new int, new int, new int, new int, new int, new int, new int, new int, new int};

*array[3] = 32; // [] has higher precedence than * so this is like *(array[3])

// remember to loop through and delete each one
for (int i = 0; i < 10; ++i)
    delete array[i];
Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
0

In your examples, you're trying to initialize arrays of pointers. Basically, I think there's no way to initialize pointer to array, except for

int array[] = {0,2,3,4};
int *ptr = array;

But honestly, I'm not sure if you asked for that.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
0

in general:

  • The symbolic name of an array (int arr[], the name being arr) generally works like a pointer to its head; so arr[3] == *(arr+3). (Note that C/C++ pointer arithmetic is in units of the pointer's size, not bytes.)
  • Creating an array using int* arr[] is an array of pointers to integers, not an array of integers.

In your example, you're trying to place integers into slots that are designated for pointers. It's extremely unlikely that you want to do that.

BRPocock
  • 13,638
  • 3
  • 31
  • 50
0

array itself is a pointer

it points to base address

this will help

http://pw1.netcom.com/~tjensen/ptr/ch2x.htm

Md Faisal
  • 2,931
  • 8
  • 29
  • 34
  • 1
    array itself is *not* a pointer, but it will be implicitly decomposed to one. – John Dibling Dec 05 '11 at 20:57
  • well it points to base address and whats the difference then – Md Faisal Dec 05 '11 at 21:05
  • For an example of what the difference is, consider the following code: ` int ary[10]; cout << sizeof(ary) << "\n"; int * p = new int[10]; cout << sizeof(p) << "\n";` If `ary` *was a pointer*, the they would output the same sizes. Try it, and I think you will find that they don't. – John Dibling Dec 05 '11 at 21:09
0

No, because pointers have to point at an object, and you're pointing it at an initializer list, not an array object. You have to instantiate an array object with the initializer list for the pointer to point at.

Similarly, you can't have

int* = &7;
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
0

When you pass an array, you actually pass a pointer that points to the first element of the array. So you should probably stick to not mix arrays and pointers to arrays. As pointed out earlier, arrays are implicitly represented as pointers. If you are just starting out, first study basic arrays, then pointers and then move on to dynamic memory allocation. Pointers are very tricky, so you might wanna go slow and thoroughly with it. It will save you a lot of time later.

devjeetroy
  • 1,855
  • 6
  • 26
  • 43
0

When you write

int* array[10]; 

You're not actually creating an array of integers, or for that matter, an array of pointers to integers. What you are doing is alloctaing 40 bytes of data (since an integer takes up 4 bytes).

Monkeyanator
  • 1,346
  • 2
  • 14
  • 29