简体   繁体   English

C结构指针-如何从模块返回结构指针?

[英]C struct pointer - how to return struct pointer from module?

I have 3 different files: main.c, module.h and module.c 我有3个不同的文件:main.c,module.h和module.c

The module.c should "transmit" 2 text messages to the main: module.c应该向主机“传输” 2条文本消息:

  • One "info" message 一条“信息”消息
  • And one "error" message. 和一个“错误”消息。

Those 2 messages are generated within the module.c 这2条消息是在module.c中生成的。

The idea is passing both messages using pointer to struct. 这个想法是通过使用指向struct的指针传递这两个消息。 Unfortunately I am missing something about pointer because only the first message ("This is info") goes through... The second one gets lost somewhere in between. 不幸的是,我缺少有关指针的信息,因为只有第一个消息(“这是信息”)通过了...第二个消息介于两者之间。

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

And the module 和模块

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

Thank you in advance for helping me. 预先感谢您对我的帮助。 Stephane 斯蒂芬

Make changes in your module code and main functions. 更改模块代码和主要功能。 Allocate struct on heap in module section and return that structure. 在模块部分的堆上分配结构,然后返回该结构。 In main function why you're allocating a struct and overwriting it with return struct from moduleFcn()? 在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;
}

In main() do the following changes. 在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM