18

I came across this question, while reading about std::array and std::vector.

Community
  • 1
  • 1
viral
  • 4,168
  • 5
  • 43
  • 68

1 Answers1

22

A C-Style array is just a "naked" array - that is, an array that's not wrapped in a class, like this:

char[] array = {'a', 'b', 'c', '\0'};

Or a pointer if you use it as an array:

Thing* t = new Thing[size];
t[someindex].dosomething();

And a "C++ style array" (the unofficial but popular term) is just what you mention - a wrapper class like std::vector (or std::array). That's just a wrapper class (that's really a C-style array underneath) that provides handy capabilities like bounds checking and size information.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
  • 1
    Still more common to think of std::vector<> as the C++ array than std::array<> – Martin York Aug 20 '11 at 06:11
  • @Keith not by a strict definition but you can use it as one with nearly identical effects. – Seth Carnegie Aug 20 '11 at 14:52
  • @Seth: Perhaps, but the common misconception that arrays are really just pointers causes a lot of problems. Perhaps it's clearer to say that array *objects* are not pointer *objects*. (Array *expressions* do usually -- but not always -- decay to pointer *expressions*.) – Keith Thompson Aug 20 '11 at 14:57
  • @Keith yes you're right. If you think that difference is important enough to this questioner then I will add a note in my answer to that effect. My point was to show him how items are grouped in a structure that is commonly called an array, and since whenever you try to do almost anything with an array it becomes a pointer, I thought is put that in there too. I would add though that a vector isn't an array either and there's not really such a thing as C++ style arrays in the strictest sense, but I thought everyone would know I'm not giving a pedantic definition of the term. – Seth Carnegie Aug 20 '11 at 15:12
  • @Keith also so I can show other people when they ask, can you give me a reference for some problems not knowing the difference between arrays and pointers causes in practice? I never knew the difference for a long time and don't remember having any problems. – Seth Carnegie Aug 20 '11 at 15:17
  • 1
    @Seth: For example, you can have a variable and a parameter with seemingly identical declarations (`int arr[42];`), but applying `sizeof` to the variable gives you the array size, while applying `sizeof` to the parameter gives you the size of a pointer. The language goes to a lot of effort to make it *seem* like arrays and pointers are interchangeable, by interpreting array parameter declarations as pointer declarations and by converting most array expressions to pointer type. Which means you can get away with conflating them *most* of the time -- and then some corner case bites you. – Keith Thompson Aug 20 '11 at 20:03
  • Doesn't the second block code have a memory leak? Or is the `delete[]` left as an exercise to the reader? – deworde Jul 05 '19 at 16:30