【问题标题】:C struct pointer - how to return struct pointer from module?C 结构指针 - 如何从模块返回结构指针?
【发布时间】:2017-06-13 12:39:35
【问题描述】:

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

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

  • 一条“信息”消息
  • 还有一条“错误”消息。

这两条消息是在 module.c 中生成的

这个想法是使用指向结构的指针传递两个消息。不幸的是,我遗漏了有关指针的一些内容,因为只有第一条消息(“这是信息”)通过...第二条消息在两者之间的某个地方丢失了。

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

提前感谢您帮助我。 斯蒂芬

【问题讨论】:

  • 首先,您不能返回指向局部变量的指针。从函数返回后,局部变量会消失,指向它的指针没有意义。其次,为什么要花4行创建text,然后立即用moduleFun返回的值覆盖它?
  • @DYZ,我同时使用了 4 行作为注释行 //text = moduleFcn() => 仅用于“理解”出了什么问题...

标签: c pointers module


【解决方案1】:

更改您的模块代码和主要功能。在模块部分的堆上分配结构并返回该结构。在主函数中,为什么要分配一个结构并用 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() 中进行以下更改。

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

【讨论】:

  • 非常感谢。解决了:-)
猜你喜欢
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-09
  • 1970-01-01
相关资源
最近更新 更多