lavr2004
lavr2004

Reputation: 51

C++ - How to fill array using pointers?

I am learning C++, but I don't completely understand the mechanic of using pointers.

How can I achieve filling array tab2 using pointers in this code:

int * tab1 = new int[10];
int * tab2 = new int[10];

for (int i = 0; i < 10; i++){
  tab1[i] = i;
  *tab2 = i; 
  tab2++;
}
for (int i = 0; i < 10; i++){ 
  std::cout << tab1[i] << "\t" << tab2[i] << std::endl;
}

The teacher in my school doesn't explain it clearly and I don't understand how to adjust array elements using pointers and putting new values in it. Please, help me understand a correctly working example with it.

Upvotes: 0

Views: 15412

Answers (3)

Neil Steyn
Neil Steyn

Reputation: 11

Rewrite your loop as below

for (int i = 0; i < 10; i++)
{
    tab1[i] = i;
    *(tab + i) = i;
}

With tab1 your currently using array syntax to add values to the dynamic array.

tab[i] = i;

if you want to fill tab2 using pointer syntax, you do it as follow:

*(tab2 + i) = i; 

This way your not changing the address of pointer tab2, your only accessing the elements.

However, when you alter tab2 directly, your actually changing the value stored in pointer tab2, so you need to set it back to the first element here's how you could do it this way:

for (int i = 0; i < 10; i++)
{
    tab1[i] = i;
    tab2 += i;
    *tab2 = i;
    tab2 -= i;
}

Upvotes: 0

ShiroKaze
ShiroKaze

Reputation: 1

It's hard to guess what specifically is confusing you. I'll try to be general. An array is a continuous space in memory, it is allocated either statically

int arr[10];

or dynamically

int *arr = new int[10];

Arrays are accessed using pointers. The pointer stores a value which references a single element of an array. Usually the first one.

In your program you can then use two ways to access an array. Either using the square brackets and putting in the number of an element starting from 0.

arr[0] = 1;

Or using the * operator and accessing the array directly.

*arr = 1;
arr++;
*arr = 2;

The code above stores one in the first element, increases the value of the pointer, then store two in the second element.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409166

When you do tab2++ you lose the original pointer.

And since both tab1 and tab2 are pointer, you are already doing it with pointers. Fact: An expression like tab1[i] is exactly the same as *(tab1 + i) (and that's valid for any pointer or array).

And if your teacher want you to use increment, then use another pointer variable that you increase. Like

int * tab3 = tab2;
for (...) { ...; *tab3++ = i; }

Now you can still use tab2 without problems.

Upvotes: 2

Related Questions