How do I change this declaration?

I have been assigned a title with the following declaration:

//The index of 1 is used to make sure this is an array.
MyObject objs[1];

However, I need to make this array dynamically the size that the program starts. I would have thought that I should just declare it as MyObject * objs; but I believe that if the original programmer declared it this way, there are some reasons for this.

Anyway, can I resize dynamically? Or should I just change it to a pointer and then malloc ()?

Can I use some new keyword for this?

+3
source share
8 answers

You're right. If you want to dynamically create an instance of your size, you need to use a pointer.

( ++, new malloc?)

MyObject* objs = new MyObject[size];
+6

STL vector:

#include <vector>

std::vector<MyObject> objs(size);

. , , C [] . , &objs[0] - list - .

+16

, malloc() it?

, malloc'd? - - std::vector.

+3

, . - len char .

:

union small_string {
   struct {
      char len;
      char buff[1];
   };
   short hash;
};

small_string malloc, , c cast reinterpret_cast

small_string str = (small_string) malloc(len + 1);
strcpy(str.buff, val);

int fast_str_equal(small_string str1, small_string str2)
{
   if (str1.hash == str2.hash)
      return strcmp(str1.buff, str2.buff) == 0;
   return 0;
}

, ++. , , .

, , ++.

+1

-?

, , -

struct foo {
/* optional stuff here */
int arr[1];
}

malloc , sizeof (struct foo), arr .

C, C, , .

, , , STL.

+1

STL , , : std::vector. , std:: list.

0

- , .
sizeof (objs);

MyObj *arr1 = new MyObj[1];
MyObj arr2[1];

sizeof(arr1) != sizeof(arr2)

, - .

0

. , .

, - "" . (a[2] , 2[a]: .. a ( , , )).

Since array syntax is pretty much syntactic sugar, switching to a pointer makes sense. But if you do, then using it new[]will make more sense (because you call your constructors for free), and switching from std::vectormakes even more sense (because you do not need to remember, call delete[]every place where the array goes out of scope due to return , break, end of instruction, exception exceptions, etc.).

0
source

Source: https://habr.com/ru/post/1706080/


All Articles