我有这个问题。我有一个填充结构的函数 create_message
struct message {
struct header{
char *protocol_version;
char *type;
long int sequence_number;
}header;
struct body
{
int num_tag;
char *tag_labels[LEN];
int num_attr_tag[LEN];
char *attr_labels[LEN][LEN];
char *attr_values[LEN][LEN];
char *attr_types[LEN][LEN]; }body;
};
create_message 的代码是:
void create_message(struct message *msg, CharmsMsg *chmsg, char *protocol_version)
{
int i,j,n;
XTypes type = chmsg->type;
printf("Tipo %ld\n", chmsg->type);
msg->header.protocol_version = (char *) malloc(sizeof(char)*STRLEN);
msg->header.protocol_version = protocol_version;
msg->header.type = (char *) malloc(sizeof(char)*STRLEN);
msg->header.type = metadati[type].typemsg;
msg->header.sequence_number = chmsg->SeqNo;
msg->body.num_tag = metadati[type].num_tag;
n=0;
for(i=0;i<msg->body.num_tag;i++)
{
// assegno le etichette ai tag
msg->body.tag_labels[i] = (char *) malloc(sizeof(char)*STRLEN);
msg->body.tag_labels[i] = metadati[type].tag_labels[i];
msg->body.num_attr_tag[i] = metadati[type].num_attr_tag[i];
for(j=0;j<msg->body.num_attr_tag[i];j++)
{
msg->body.attr_labels[i][j] = (char *) malloc(sizeof(char)*STRLEN);
msg->body.attr_labels[i][j] = metadati[type].attr_labels[i][j];
// assegno il valore dell'attributo j-esimo al tag i-esimo
msg->body.attr_values[i][j] = (char *) malloc(sizeof(char)*STRLEN);
msg->body.attr_values[i][j] = ((getDati[type])(chmsg->structCHARMS))[n++];
printf("IN create_message: Contenuto buf[%d] %s\n",(i+j), msg->body.attr_values[i][j]);
// assegno il tipo dell'attributo j-esimo al tag i-esimo
msg->body.attr_types[i][j] = (char *) malloc(sizeof(char)*STRLEN);
msg->body.attr_types[i][j] = metadati[type].attr_types[i][j];
}
}
}
特别是 create_message 调用 getDati[type] ,它是一个指向函数的数组。该数组中的一个特定函数是 getRegisterMe,如下所示
char **getRegisterMe(void *structCHARMS)
{
ClientData *client = (ClientData *)structCHARMS;
char *buf[3];
int i;
for(i=0; i< 3; i++)
buf[i] = (char*)calloc(MAX_SEQ_LEN, sizeof(char));
//attributi del tag[0]:Cookie
sprintf(buf[0], "%d", client->cookie_value);
//attributi del tag[1]:Register
sprintf(buf[1], "%s", addrtostr(client->local_addr));
sprintf(buf[2], "%d", client->mode);
printf("IN getData buf[0]%s\n",buf[0]);
printf("IN getData buf[1]%s\n",buf[1]);
printf("IN getData buf[2]%s\n",buf[2]);
return (char **)buf;
}
当我启动程序时,我发现 getRegisterMe 没有正确填充 struct struct message 的元素。事实上,我观察到这一点:
IN getData buf[0]0
IN getData buf[1]127.0.0.1:53285
IN getData buf[2]3
IN create_message: Contenuto buf[0] ? ?V??FR?
IN getData buf[0]0
IN getData buf[1]127.0.0.1:53285
IN getData buf[2]3
IN create_message: Contenuto buf[1] H??H???H??t?
IN getData buf[0]0
IN getData buf[1]127.0.0.1:53285
IN getData buf[2]3
IN create_message: Contenuto buf[2]
为什么 getRegisterMe 中打印的 char*buf 的值与 msg->body.attr_values 打印的值不匹配?谁能帮我?