简体   繁体   中英

C struct pointer - how to return struct pointer from module?

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

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

  • One "info" message
  • And one "error" message.

Those 2 messages are generated within the module.c

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

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

/*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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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