【发布时间】: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() => 仅用于“理解”出了什么问题...