本文介绍了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

推荐答案

/*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;
}
/*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结构指针-如何从模块返回结构指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 21:00