-1

I am trying to understand arrays and pointers in c++. In a past project, I did. I created a pointer and then assigned that pointer to an array of the same type. I've read previous posts, though, that says you can't assign a pointer to an array. Also from the pointer, I was able to use the index to get a certain element (square brackets []).

So I was wondering if anyone could explain to me arrays and pointers in C++ and why something like this is possible, I've tried looking for it online, but haven't found anything. Example,

    #include <iostream>
    using namespace std;

    int main()
    {
    int *pointer = new int[10];

    for (int i = 0; i < 10; i++)
    {
        pointer[i] = i;
    }

    for (int i = 0; i < 10; i++)
    {
        cout << pointer[i];
    }

    return 1;
    }
Jack
  • 3
  • 1
  • 3

3 Answers3

0

a pointer in reality is a variable which keeps an address of a memory it points to. The memory itself can be allocated by one of the heap management functions like 'malloc' or 'new' or some others. So, in general you ask the function to allocate a certain amount of memory and return its address. You keep the latter as the pointer to it in a variable.

Arrays in 'c++/c' are contiguous chunks of memory. So, there is no difference between allocating 40 bytes or 10 integers in the array (assuming that an int is 4 byte long).

'c/c++' also understand the type of the data which the allocated memory contains. The languages provide a feature named 'pointer arithmetic'. This actually means that you can add to a pointer or subtract from it. The language will factor the values by the size of the type. I.e.

int *a = new ...
int b = *(a+4);

In the above case value of 'b' will be the same as the value saved in memory 'a' with offset of 16 bytes.

The above is very similar to the array indexing arithmetic and the language allow you to use the array indexing instead of the above:

b = a[4];

So, in this sense both worlds intersect and you can interchangeably use either pointer arithmetic or array arithmetic in the language.

Arrays do not have to be allocated on the heap as well as the pointers do hot have to address the heap only. You can have an array allocated on stack or in the global scope and have a pointer to it:

int myarray[10];
int *pointer = myarray;

How you can apply either the pointer arithmetic or array arithmetic to the pointer. the following are equivalent (if you did not advance the pointer)

myarray[3]
pointer[3]
*(pointer + 3)

Hope it clarifies the issue for you.

Serge
  • 11,616
  • 3
  • 18
  • 28
  • Misleading: "can be allocated by one of the heap management functions like 'malloc' or 'new' or some others." Heap doesn't even enter the equation. Anything with an address can be pointed at, Automatically allocated storage (you address this later) and hardware are also popular. Plus the implementation may not even have a heap. This makes "So, in general you ask the function to allocate a certain amount of memory and return its address." mostly wrong. – user4581301 Sep 15 '17 at 22:25
  • "The above is very similar to the array indexing" guaranteed, actually. – user4581301 Sep 15 '17 at 22:27
0

The main difference between arrays and pointers is that they are completely different things.

As array is a collection of objects, which is laid out contiguously in memory. For example, int x[5] defines an array named x, which is a collection of 5 integers, laid out side by side in memory. Individual elements in the array may be accessed using "array syntax" of the form x[i] where i is an integral value with values between 0 and 4. (Other values of i will result in undefined behaviour).

A pointer is a variable which holds a value that is an address in memory. For example, int *p defines p as a pointer to an int, and it can be initialised with the address of a variable of type int. For example, p = &some_int causes p to contain the address of some_int. When that is done, the notation *p (called dereferencing) provides access to the pointed-to variable. For example, *p = 42 will set some_int to have the value 42.

You'll notice, in the description above, I have not used the word "pointer" in describing an array, nor have I used the word "array" to describe a pointer. They are completely different things.

However, they can be used in ways that makes them seem the same, because of a few rules in the language. Firstly, there is a conversion called the "array-to-pointer" conversion. Because of this, it is possible to do

  int x[5];
  int *p = x;

The initialisation of p actually works by using the array-to-pointer conversion. Because it is being used to initialise a pointer, the compiler implicitly converts x to a pointer, equal to the address of x[0]. To do this explicitly (without the compiler silently and sneakily doing a conversion) you could have written

  int *p = &x[0];

and got exactly the same effect. Either way, the assignment *p = 42 will subsequently have the effect of assigning x[0] to 42.

That suggests there is a relationship between expressions involving pointers and expressions involving (the name of) arrays. If p is equal to &x[0], then

  • p + i is equivalent to &x[i]; AND
  • *(p + i) is equivalent to x[i].

The language rules of C and C++ make these relationships symmetric, so (look carefully here)

  • x + i is equivalent to &x[i]; AND
  • *(x + i) is equivalent to x[i]

and, with pointers

  • p + i is equivalent to &p[i]; AND
  • *(p + i) is equivalent to p[i]

Which basically means that pointer syntax can be used to work with arrays (thanks to the pointer-to-array conversion) AND array syntax can be used to work with pointers.

Really bad textbooks then go on from this and conclude that pointers are arrays and that arrays are pointers. But they are not. If you find textbooks which say such things, burn them. Arrays and pointers are different things entirely. What we have here is a syntactic equivalence - even though arrays and pointers are different things entirely, they can be worked on using the same syntax.

One of the differences - where the syntactic equivalence does not apply - is that arrays cannot be reassigned. For example;

 int x[5];
 int y[5];
 int *p = y;    //   OK  - pointer to array conversion

 x = y;       // error since x is an array
 x = p;       // error since x is an array

The last two statements will be diagnosed by a C or C++ compiler as an error, because x is an array.

Your example

 int *pointer = new int[10];

is a little different again. pointer is still not an array. It is a pointer, initialised with a "new expression", which dynamically allocates an array of 10 integers. But because of the syntactic equivalence of pointers and arrays, pointer can be treated syntactically AS IF it is an array of 10 elements.

Note: the above is concerned with raw arrays. The C++ standard library also has a type named std::array which is a data structure which contains an array, but behaves somewhat differently than described here.

Peter
  • 35,646
  • 4
  • 32
  • 74
  • Thank you, I was having trouble understanding why a pointer seemed to behave like an array at times. I wrote a program recently for a school project where I used similar code to what I posted (can't post actual code), and was just really confused that I could do this. I actually used this to create an adjacency list. where I had a node object and created a node of type node (e.g. edgeNode adjNode = new edgeNode[10]). Your reply helped me understand why this works. – Jack Sep 16 '17 at 22:06
-2

From wikipedia:

A pointer references a location in memory, and obtaining the value stored at that location is known as dereferencing the pointer

Arrays are the contiguous memory locations and their location in memory is referenced by a pointer.

int *pointer = new int[10];

for (int i = 0; i < 10; i++)
{
    pointer[i] = i;
}

the code above is actually accesses pointer + i * sizeof(int) thanks to operator[] (assume variable pointer is an integer or smth like that, no pointer arithmetic here.)

Shine
  • 103
  • 1
  • 4
  • 3
    Very sorry, but "their location in memory is referenced by a pointer." is not true. An array knows the beginning and the size. A pointer only knows that it points somewhere. – user4581301 Sep 15 '17 at 22:00