C/ c++更好的写法

C/C++ Better way to write this?

本文关键字:更好 c++      更新时间:2023-10-16

我正在尝试编写易于调试的代码。有没有更好的方法来写函数do_save():

int one;
int two[10];
char three;
...
unsigned char *state = (unsigned char*)malloc(1024);
...
void do_save()
{
    memcpy(state, &one, 4);
    memcpy(state+4, two, 40);
    memcpy(state+44, &three, 1);
}

我所说的"更好"是指一种避免产生bug的方法,因为我搞砸了大小计数,特别是当有10或20个变量要保存在状态中时。

使用struct

int one;
int two[10];
char three;
typedef struct {
    int one;
    int two[10];
    char three;
} State;
...
State *state = new State; // C++ish
State *state = malloc(sizeof(State));  //Cish
...
void do_save(State* state) {
    state->one = &one;
    memcpy(state->two, &two, sizeof(state->two));
    state->three = three;
}
有了一个结构体,你可以很容易地做很多事情。例如,您可以将当前状态和保存状态分开,并且可以使用等号来完成保存/恢复。使用read/fwrite写入二进制文件很容易。你可以把你的状态结构放在堆上或堆栈上,这取决于你的需要。
#include <stdlib.h>
#include <stdio.h>
typedef struct {
    int one;
    int two[10];
    char three;
} State;
void print_state(State* state) {
    printf("%i ",   state->one);
    int i;
    for (i = 0; i < 10; ++i) {
        printf("%i ",   state->two[i]);
    }
    printf("%cn",  state->three);
}
int main() {
    State* state = (State*)(malloc(sizeof(State)));
    State current_state;
    FILE* input = fopen("binary.data", "rb");
    if (input) {
        fread(&current_state, sizeof(State), 1, input);
        fclose(input);
    }
    print_state(&current_state);
    current_state.one = 1;
    int i;
    for (i = 0; i < 10; ++i) {
        current_state.two[i] = i + 1;
    }
    current_state.three = 'Z';
    *state = current_state;
    FILE* output = fopen("binary.data", "wb");
    fwrite(state, sizeof(State), 1, output);
    fclose(output);
        free(state);
}

您可以使用variable为您完成这项工作。例如:

int sizetotal = 0;
int sizethis = 0;
sizethis = sizeof(one);
memcpy(state+sizetotal, &one, sizethis);
sizetotal += sizethis;
sizethis = sizeof(*two);
memcpy(state+sizetotal, two, sizethis);
sizetotal += sizethis;
sizethis = sizeof(three);
memcpy(state+sizetotal, &three, sizethis);
sizetotal += sizethis;

正如您所看到的,这3行是重复的——所以它可以放在宏或函数中。

当然,如果这是c++的话,最好的办法就是创建一个State对象,并给它适当的方法。

看起来您正在从缓冲区状态复制连续的偏移量到其他位置。您可以通过简单地使用Struct ->将连续偏移复制到连续偏移,如下所示:

typedef struct {
    int one;
    int two[10];
    char three;
} Container;
Container  my_storage
...
unsigned char *state = (unsigned char*)malloc(1024);
...
void do_save(Container  *dest, char*src) {
   memcpy(src, state, sizeof(Container));    
}

使用c++:

    int one;
    std::array<int, 10> two;
    char three;
    std::vector<unsigned char> state(1024);
    auto start = state.begin();
    auto end = start + sizeof(one);
    std::copy(start, end, &one);
    start = ++end;
    end += two.size();
    std::copy(start, end, two.begin());
    start = ++end;
    end += sizeof(three);
    std::copy(start, end, &three);