[英]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.