Pointer to Array or direct access to array

Hi CPlusPlus community! :)

I'm begin in C++ and I have a question about pointers and array.

If I write this :

1
2
3
4

string myArray[23][2];
string* myPointer = myArray[0];


My pointer of string will point on my first element of array, at position 0. But, if I want to create an object with my information on my array, is it more effective to use the pointer or the array directly?
Example :

1
2
3
4

OMusic MyMusic(myArray[23][0], myArray[23][1]); // Use this or
OMusic MyMusic(myPointer[0], myPointer[1]); // this?

where OMusic is an object. What is more effective? It has?

Thanks!
Last edited on
There is effective and there is effective.

You might achieve something efficient with plain arrays and/or raw pointers, but it can become complex, error-prone, and more difficult to change later.

The other effective is code that is correct and easy to understand. For that, there are pre-made building blocks that in itself are correct. We can focus on using the blocks correctly, rather than both creating and using blocks simultaneously. The C++ Standard Library.

We can create some blocks to emphasize the logic in our program.


You do have a table (two columns, many rows) with 46 pieces of text in it. It is impossible to guess from names like "myArray" what logical things are in the table. What does one row of the table contain?


A function can take an argument by reference. No copy is made.

There is a std::vector that is kind of an array with a lot of syntactic sugar on it. A vector is one object, unlike an array that has many objects.

Arrays arguments are not copied either. The function actually receives a pointer. Array decays to a pointer.


Correctness. Clarity.

You have:
1
2
3
4
5
string myArray[23][2]; // a table
string * myPointer = myArray[0]; // pointer to first row?

OMusic foo( myArray[23][0], myArray[23][1] );
OMusic bar( myPointer[0], myPointer[1] );

The bar receives two strings, the myArray[0][0] and myArray[0][1]. The strings from the first row of the table.

The foo seems to receive two strings too. However, the myArray does not have myArray[23]. The myArray has only 23 rows. The myArray[23] would be 24th row.


Both myArray and myPointer need about the same amount of pointer math when you do dereference them. A pointer is an additional object and thus it occupies some additional memory.
keskiverto, Thanks! It was very helpful! :)
Topic archived. No new replies allowed.