C结构指针-如何从模块返回结构指针? [英] C struct pointer - how to return struct pointer from module?

查看:75
本文介绍了C结构指针-如何从模块返回结构指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个不同的文件:main.c,module.h和module.c

I have 3 different files: main.c, module.h and module.c

module.c应该向主机传输" 2条文本消息:

The module.c should "transmit" 2 text messages to the main:

  • 一条信息"消息
  • 还有一条错误"消息.

这2条消息是在模块内生成的.c

Those 2 messages are generated within the module.c

这个想法是使用指针将两个消息都传递给struct.不幸的是,我缺少关于指针的信息,因为只有第一个消息(这是信息")通过了...第二个消息在两者之间丢失了.

The idea is passing both messages using pointer to 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;
}

还有模块

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

预先感谢您对我的帮助. 斯蒂芬(Stephane)

Thank you in advance for helping me. Stephane

推荐答案

更改模块代码和主要功能.在模块部分的堆上分配结构,然后返回该结构.在main函数中,为什么要分配一个结构并用来自moduleFcn()的return结构覆盖它?

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()?

/*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()中进行以下更改.

In main() do the following changes.

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

这篇关于C结构指针-如何从模块返回结构指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆