gpt4 book ai didi

c++ - C/C++ 更好的写法?

转载 作者:太空宇宙 更新时间:2023-11-04 05:26:48 25 4
gpt4 key购买 nike

我正在尝试编写易于调试的代码。有没有更好的方法来编写函数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);
}

当我说更好时,我指的是一种避免产生错误的方法,因为我弄乱了大小计数,尤其是当有 10 或 20 个变量要保存在状态中时。

最佳答案

使用结构。

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;
}

一旦有了结构,您就可以轻松地做很多事情。例如,您可以将当前状态和保存状态分开,保存/恢复可以用等号来完成。使用 fread/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("%c\n", 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);
}

关于c++ - C/C++ 更好的写法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22425812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com