Я хочу выделить память для частного массива uint32_t в классе A
с помощью функции allocate_buffer(...)
, которая принимает размер массива и указатель неинициализированного указателя (void *data
).
Указатель следует использовать для доступа к памяти A::buffer
, чтобы можно было использовать memcpy(...)
для копирования данных в массив с помощью
memcpy(pointer_to_buffer, some_src_data, sizeof(some_src_data));
prg.hpp
класс с приватным буфером и функциями для выделения и печати
#ifndef PRG_HPP
#define PRG_HPP
#include <cstdint>
#include <stddef.h>
#include <cstdlib>
#include <iostream>
class A {
private:
void *buffer;
size_t count;
public:
void allocate_buffer(size_t size, void **data) {
buffer = malloc(size);
count = size;
data = &buffer;
}
void print_buffer() {
auto data = (uint32_t*)buffer;
for (size_t i = 0; i < count; i++) {
std::cout << data[i] << std::endl;
}
}
};
#endif
main. cpp
простая программа, использующая prg.hpp
#include "prg.hpp"
#include <iostream>
#include <vector>
#include <cstring>
int main(void) {
// An objected of class A gets created
A a = {};
// A simple vector with ints up to 100, which acts as the src for malloc
std::vector<uint32_t> ints;
for (int i = 0; i < 100; i++) {
ints.push_back(i);
}
// buffer of object a is allocated and data should now be a pointer to the buffer
void *data;
size_t size = sizeof(uint32_t) * ints.size();
a.allocate_buffer(size, &data);
// Using the pointer to copy the contents of the vector ints to the buffer of object a
memcpy(data, ints.data(), size);
// Presentation
a.print_buffer();
return 0;
}
PS: выполнение дает segfault