在c++中为char数组分配固定内存。

时间:2022-12-04 03:11:28

The code below presents a 2d char array with 64 blocks.

下面的代码展示了一个带有64个块的2d字符数组。

char **arr= new char*[64];
for (int i = 0; i < 64; i++) {
    arr[i] = new char[64];
}

But I want to have control over this array just as I can malloc fixed memory in C.

但是我想对这个数组进行控制正如我可以在C中malloc固定内存一样。

char **arr= malloc(sizeof(char *) * 64);
for (int i = 0; i < 64; i++) {
    arr[i] = malloc(64);
}

How can I achieve it in C++?

如何在c++中实现它?

Also, in C, we can use pointer like this:

同样,在C中,我们可以使用这样的指针:

Mystruct *next_entry = (Mystruct *) ((char*) slot + SIZE;

we can calculate the pointer address and get the next available free memory.

我们可以计算指针地址并获得下一个可用的空闲内存。

What do I need to do if I want to do the same thing in C++?

如果我想在c++中做同样的事情,我需要做什么?

1 个解决方案

#1


3  

You don't need anything extra to do the same manipulations in c++, and your new code is equivalent to your malloc code

在c++中,您不需要任何额外的操作来执行相同的操作,您的新代码就等同于您的malloc代码。

char **arr    = malloc(sizeof(char) * 64); equiv  char **arr    = new char*[64];
       arr[i] = malloc(64);                equiv         arr[i] = new char[64];

except perhaps for the probable typo in this line

除了这一行中可能出现的错字。

char **arr    = malloc(sizeof(char) * 64);

which should read

应该读

char **arr= malloc(sizeof(char *) * 64);

also this will work just as it does in c

这也和c一样。

Mystruct *next_entry = (Mystruct *) ((char*) slot + SIZE;

although even in c, i think this violates strict aliasing rules, but I am not quite sure.

虽然在c语言中,我认为这违反了严格的混叠规则,但我不太确定。

#1


3  

You don't need anything extra to do the same manipulations in c++, and your new code is equivalent to your malloc code

在c++中,您不需要任何额外的操作来执行相同的操作,您的新代码就等同于您的malloc代码。

char **arr    = malloc(sizeof(char) * 64); equiv  char **arr    = new char*[64];
       arr[i] = malloc(64);                equiv         arr[i] = new char[64];

except perhaps for the probable typo in this line

除了这一行中可能出现的错字。

char **arr    = malloc(sizeof(char) * 64);

which should read

应该读

char **arr= malloc(sizeof(char *) * 64);

also this will work just as it does in c

这也和c一样。

Mystruct *next_entry = (Mystruct *) ((char*) slot + SIZE;

although even in c, i think this violates strict aliasing rules, but I am not quite sure.

虽然在c语言中,我认为这违反了严格的混叠规则,但我不太确定。