gpt4 book ai didi

c++ - 调用使用字符数组的类函数 (C++)

转载 作者:行者123 更新时间:2023-11-30 03:43:44 26 4
gpt4 key购买 nike

我主要使用 C 语言,已经有一段时间没有使用类了。我正在尝试使用其他人创建的一些类函数,但我无法使用 deserialize() 函数。我明白它的作用,但我终究无法弄清楚如何调用这个函数。我在下面提供了函数以及我如何尝试调用它们。

//Creates a packet 
packet::packet(int t, int s, int l, char * d){
type = t;
seqnum = s;
length = l;
data = d;
}
// This function serializes the data such that type, seqnum, length, and data values are placed
// in a char array, spacket, and separated by a single space; that is, spacket contains the serialized data
void packet::serialize(char * spacket){
cout << "data: " << endl << endl;
sprintf (spacket, "%d %d %d %s", type, seqnum, length, data);
}

// This function deserializes a char array, spacket, which is the result of a call to serialize
void packet::deserialize(char * spacket){
char * itr;
itr = strtok(spacket," ");
char * null_end;

this->type = strtol(itr, &null_end, 10);

itr = strtok(NULL, " ");
this->seqnum = strtol (itr, &null_end, 10);

itr = strtok(NULL, " ");
this->length = strtol (itr, &null_end, 10);

if(this->length == 0){
data = NULL;
}
else{
itr = strtok(NULL, "");
for(int i=0; i < this->length; i++){ // copy data into char array
this->data[i] = itr[i];
}
}
}

下面是我试图让它发挥作用的方法:

packet *test = new packet(1, 4, 4, message); //message is a *char with the data
test->serialize(sendbuf); //this works correctly
packet *test2 = new packet(0,0,0, NULL); //I am not sure if I need to be creating a new packet for the deserialized information to get placed into
test->deserialize(sendbuf); //results in a segmentation fault currently

我只是不明白如何调用 deserialize(),我创建了一个数据包并将其序列化并且该部分工作正常,但我不明白如何反转它。我需要先创建一个空数据包对象吗?如果是这样,如何?我尝试过多种方式,但我无法让它工作。我知道这是非常基础的,但就像我说的,我已经有几年没有上过课了。我花了很长时间才开始序列化工作,但我已经尝试了所有我能想到的反序列化方法,但还是卡住了。

最佳答案

@Pongjazzle,

我同意 Sam 的观点,即类设计需要改进。但是,我认为您可以弄清楚。假设 sendbuf 可以保存所有序列化的数据包数据,您可能希望通过这种方式来测试您的代码。

packet *test = new packet(1, 4, 4, message);
test->serialize(sendbuf);

packet *test2 = new packet(0,0,0, NULL); // results in a segmentation fault currently (which is expected as the attempts to access a location referred to by a null pointer in this->data (i.e., NULL based on the object instantiation code)
test->deserialize(sendbuf);

将其更改为:

packet *test2 = new packet(0,0,0, newmessage); // assign a valid buffer
test2->deserialize(sendbuf); // Now fill's in the values and buffer from serialized content.

关于c++ - 调用使用字符数组的类函数 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35952788/

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