[英]C struct pointer - how to return struct pointer from module?
我有3个不同的文件:main.c,module.h和module.c
module.c应该向主机“传输” 2条文本消息:
这2条消息是在module.c中生成的。
这个想法是通过使用指向struct的指针传递这两个消息。 不幸的是,我缺少有关指针的信息,因为只有第一个消息(“这是信息”)通过了...第二个消息介于两者之间。
/*file:main.c (gcc -o test main.c module.c)*/
#include <stdio.h>
#include <stdlib.h>
#include "module.h"
static struct message *text = NULL;
int main(int argc, char **argv)
{
text = (struct message *) malloc(sizeof(struct message));
text->info_text="toto";
text->error_text="tutu";
text->id = 55;
text = moduleFcn();
printf("message->info_text: %s\n", text->info_text);
printf("message->error_text: %s\n", text->error_text);
printf("message->id: %u\n", text->id);
return 0;
}
和模块
/*module.h*/
struct message
{
char *info_text;
char *error_text;
int id;
};
extern struct message* moduleFcn(void);
/*module.c*/
#include <stdio.h>
#include "module.h"
static struct message *module_text = NULL;
struct message* moduleFcn(void)
{
struct message dummy;
module_text = &dummy;
module_text->info_text = "This is info";
module_text->error_text = "This is error";
module_text->id = 4;
return module_text;
}
预先感谢您对我的帮助。 斯蒂芬
更改模块代码和主要功能。 在模块部分的堆上分配结构,然后返回该结构。 在main函数中,为什么要分配一个结构并用来自moduleFcn()的return结构覆盖它?
/*module.h*/
struct message
{
char *info_text;
char *error_text;
int id;
};
extern struct message* moduleFcn(void);
/*module.c*/
#include <stdio.h>
#include "module.h"
struct message* moduleFcn(void)
{
struct message *dummy = (struct message*)malloc(sizeof(struct message));
dummy->info_text = "This is info";
dummy->error_text = "This is error";
dummy->id = 4;
return dummy;
}
在main()中进行以下更改。
/*file:main.c (gcc -o test main.c module.c)*/
#include <stdio.h>
#include <stdlib.h>
#include "module.h"
int main(int argc, char **argv)
{
struct message *text = moduleFcn();
printf("message->info_text: %s\n", text->info_text);
printf("message->error_text: %s\n", text->error_text);
printf("message->id: %u\n", text->id);
free(text);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.