Gilberto Marcano
Gilberto Marcano

Reputation: 9

Is this a good use/code of arrays with pointers in C++?

I'd like to ask you if you think about this code, whether it is totally bad or i'm doing a bad use of the memory

This is the code

// Ask for capacity
int capacity ;
cout << "capacity: ";
cin >> capacity;

// Declare the array with pointers, this line is very important
int *arr = new int;

// For 0 until capacity-1 print ask for the numbers
for (int i = 0; i < capacity; i++)
{
  cout << "number: ";
  cin >> *(arr + i);
}

// Print them
for (int i = 0; i < capacity; i++)
{
  cout << "[" << i << "]: " << *(arr + i) << " in " << arr + i << endl;
}

And this is an example of its output

capacity: 9
number: 1
number: 2
number: 3
number: 4
number: 5
number: 6
number: 7
number: 8
number: 9
[0]: 1 in 0x55dee480c690
[1]: 2 in 0x55dee480c694
[2]: 3 in 0x55dee480c698
[3]: 4 in 0x55dee480c69c
[4]: 5 in 0x55dee480c6a0
[5]: 6 in 0x55dee480c6a4
[6]: 7 in 0x55dee480c6a8
[7]: 8 in 0x55dee480c6ac
[8]: 9 in 0x55dee480c6b0

Look that, effectively it's saving the numbers in the correct positions in memory (4 bits, the size of an int) But what's the limit? How can I know if I'm touching memory that I shouldn't touch? Because look that I'm declaring the array as

int *arr = new int

Is that okay?

the same with this code, but this could be a little bit worse because it's a string, an array of characters as you may know

// Declaring the pointer name as new char and ask for it
char *name = new char;
cout << "name in: ";
cin >> name;
cout << "name out\n";
for (int i = 0; *(name + i) != '\0' ; i++)
{
  printf("[%i]: %c\n", i, *(name + i));
}

Example:

name in: Gilberto       
name out
[0]: G
[1]: i
[2]: l
[3]: b
[4]: e
[5]: r
[6]: t
[7]: o

Upvotes: 0

Views: 75

Answers (2)

Jesper Juhl
Jesper Juhl

Reputation: 31459

Raw (owning) pointers and manual memory management is almost never a good idea in modern C++. You should use containers like std::array and std::vector rather than C-style arrays any day. And ownership and lifetime of dynamic resources is much better modeled with smart pointers like std::unique_ptr, std::shared_ptr & std::weak_ptr rather than raw pointers. Don't write code that's easy to get wrong. Use the facilities we have available, to write code that's easy to get right and hard(er) to get wrong.

Upvotes: 0

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136425

The code only allocates one int object. Fix:

int* arr = new int[capacity];

*(arr + i) can be simpler: arr[i].


The code needs to delete the array at the end:

delete[] arr;

Or, better, use a smart pointer to avoid having to delete manually:

std::unique_ptr<int[]> arr(new int[capacity]);

Or, even better, use std::vector<int> arr(capacity);.

Upvotes: 2

Related Questions