c++ - 用 C 重写 C++ 类

标签 c++ c arrays memory-management struct

这个问题在这里已经有了答案:





How to find the 'sizeof' (a pointer pointing to an array)?

(17 个回答)


1年前关闭。




所以,我在重写我用 C 语言制作的 C++ 类时遇到了一些麻烦。
C++ 类有一些私有(private)属性:

int grid_width;
int grid_height;
const int group_width = 2;
const int group_height = 4;
std::vector<int> buffer;
它是这样初始化的:
grid::grid(int width, int height) {
            this->grid_width = width;
            this->grid_height = height;
            buffer.resize(this->grid_width / this->group_width * this->grid_height / this->group_height, 0);
    
}
它还带有一个清晰的功能,如下所示:
void grid::clear() {
    // get_buffer_size returns elements in the buffer vector
    for (int i = 0; i < get_buffer_size(); ++i) {
        buffer[i] = 0x00;
    }
}
现在,我用 C 重写它的尝试看起来有点像这样:
typedef struct
{
    int width;
    int height;
    int *buffer;
} grid;

grid *grid_new(int grid_width, int grid_height)
{
    if ((grid_width % 2 != 0) || (grid_height % 4 != 0))
        return NULL;

    int group_height = 4;
    int group_width = 2;

    grid *p_grid = calloc(grid_width / group_width * grid_height / group_height, sizeof(int));
    p_grid->width = grid_width;
    p_grid->height = grid_height;

    return p_grid;
}

void grid_free(grid *p_grid)
{
    free(p_grid->buffer);
    free(p_grid);
}

void grid_clear(grid *g)
{
    // ToDo: Iterate over all elements in the buffer
    int elements = sizeof(g->buffer) / sizeof(int);
    printf("Elements: %i", elements);
}
但是由于某种原因,我的 C 代码中的元素数量总是 2?
有谁知道我在哪里搞砸了?
如果网格初始化为 4 和 8,则预期缓冲区大小应为 4,而不是 2。如果将其初始化为 10 和 24,则预期大小将为 30,但在我的 C 示例中仍为 2。

最佳答案

您的 grid_new正在分配 grid 的数组结构而不是单个 grid具有正确数量的元素。
您需要设置buffer此外,网格中的元素数量基于宽度/高度,而不是 sizeof(g->buffer)这是指针的大小,而不是它指向的区域
这是重构的代码:

const int group_height = 4;
const int group_width = 2;

typedef struct {
    int width;
    int height;
    int *buffer;
} grid;

grid *
grid_new(int grid_width, int grid_height)
{
    if ((grid_width % 2 != 0) || (grid_height % 4 != 0))
        return NULL;

    grid *p_grid = calloc(1,sizeof(*p_grid));

    // FIXME -- why???
    grid_width /= group_width;
    grid_height /= group_height;

    p_grid->width = grid_width;
    p_grid->height = grid_height;

    p_grid->buffer = calloc(grid_width * grid_height,sizeof(int));

    return p_grid;
}

void
grid_free(grid *p_grid)
{
    free(p_grid->buffer);
    free(p_grid);
}

void
grid_clear(grid *g)
{
    // ToDo: Iterate over all elements in the buffer
    int elements = g->width * g->height;

    printf("Elements: %i", elements);
}

关于c++ - 用 C 重写 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62626082/

相关文章:

c++ - std::thread 从模板函数调用模板函数

适合初学者的 C++ 类实现

c - 以下功能无法按预期工作

javascript - AngularJS - ng-repeat array with string index

c# - 如何使用 MongoDB 访问深层嵌套数组(ASP.NET Core 2.2)

c++ - 如何删除 QToolButton 上的轮廓

c++ - 如何将表示像素的字符数组读取为 unsigned int

objective-c - 移动数组中的每个对象?

c# - 从 C# .NET 调用使用 C 样式数组作为参数的 C 方法

c - Keil Uvision 5 添加头文件和源文件?