0

Are there any advantage of using normal arrays over array of pointers(and vice-versa)?

When should I use array of pointers and when should I avoid it?

In college, everyone seems to be crazy about pointers. I know std::vector is an easy way out, but it is prohibited to use in college. We're asked to solve stuff without STL for now.

I got an answer from SO (link), but the answer went way over my head.

For example: Is using int array[] better or is int* parray[] better?

14
  • 6
    What is a pointer array? Commented Jul 11, 2014 at 22:11
  • 1
    BTW, if they won't let you use the C++ standard library in a C++ course, they are basically making you write C. Commented Jul 11, 2014 at 22:12
  • An array of pointers sounds like a multidimensional array to me... Do you mean: int * pointer = new int(5) vs int array[5]? Commented Jul 11, 2014 at 22:16
  • @JosephMansfield We are strictly asked to use only pointers. Commented Jul 11, 2014 at 22:17
  • If the question is whether use arrays of concrete objects or arrays of pointers to this objects. I'll go with the first. Always try to have your memory compact. Commented Jul 11, 2014 at 22:18

1 Answer 1

1

int array[] is an array of an int. What it means is it will hold a collection of multiple integer numbers. Imagine it as a place holder that holds a number of integers. When you use int array[] in C++, you must give it a fixed size before you use it:

int array[5]

and the size will be put inside the square bracket [], otherwise it won't compile and will give you error. The disadvantage of using this normal array is you have to know the size of the array first, otherwise the program won't run. What if your estimation size is different from actual use ? What if your estimation is much much larger than the real value ? It will cost you a lot of memory.

int *array[] is not valid in C++. If you want to do a pointer to an array without knwoing the size of the array at run time. Do this:

int *p;
int size;

cout << "How big is the size ?";
cin >> size;

p = new int[size];

That way, you don't need to know the value of size before run time, thus you won't waste memory.

Sign up to request clarification or add additional context in comments.

4 Comments

AAAH! Makes more sense now. I was waiting for this answer!
(how did that answer get here? There wasn´t one past closing before)
@Hoang Minh: Your answer is missing a good part.
@deviantfan: I posted the answer before someone closed it, but wasn't sure that what the poster asked for, so I deleted it, and ask him again and went back to edit my answer. About the missing part, could you elaborate ? Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.