这个想法是格式化模块内结构的文本信息消息。当尝试使用 (cf module.c) 定义消息时,它就像一个魅力:
/*this works*/
module_text3.info_text[0] = "toto[0]";
module_text3.info_text[1] = "toto[1]";
但是当使用sprintf时,我遇到了分段错误(cf module.c):
/*this gives segmentation fault*/
for(cpt=0; cpt < 2; cpt++)
{
sprintf(module_text3.info_text[cpt], "info[%u]", cpt);
}
3个不同的文件:main.c,module.h和module.c
/*main.c*/
/*gcc -o test main.c module.c*/
#include <stdio.h>
#include "module.h"
int main(int argc, char **argv)
{
int i;
struct message3 *ptext3 = moduleFcn3();
for (i= 0; i < ptext3->info_nb; i++)
{
printf("ptext3->info_text[%u]: %sn", i, ptext3->info_text[i]);
}
printf("ptext3->error_text: %sn", ptext3->error_text);
printf("ptext3->id: %un", ptext3->id);
printf("ptext3->info_nb: %un", ptext3->info_nb);
printf("ptext3->info_nb_max: %un", ptext3->info_nb_max);
return 0;
}
/*------------------------------------------------------*/
/*module.h*/
#define NB_LINE_MAX 10
struct message3
{
char *info_text[NB_LINE_MAX]; /*a few info lines.*/
char *error_text; /*only one line for error.*/
int id;
int info_nb_max;
int info_nb;
};
extern struct message3* moduleFcn3(void);
/*------------------------------------------------------*/
/*module.c*/
#include <stdio.h>
#include "module.h"
/*static is in "Stack".*/
static struct message3 module_text3;
struct message3* moduleFcn3(void)
{
int cpt = 0;
struct message3 *ptext;
/*this gives segmentation fault*/
for(cpt=0; cpt < 2; cpt++)
{
sprintf(module_text3.info_text[cpt], "info[%u]", cpt);
}
/*this works*/
// module_text3.info_text[0] = "toto[0]";
// module_text3.info_text[1] = "toto[1]";
// cpt = 2;
module_text3.error_text = "This is error";
module_text3.id = 4;
module_text3.info_nb_max = NB_LINE_MAX;
module_text3.info_nb = cpt;
ptext = &module_text3;
return ptext;
}
我将不胜感激任何关于如何格式化我的信息消息的建议(使用我们不使用 sprintf)。谢谢,
尚未为 info_text
字段中的字符串分配空间。最简单的方法是更改struct
:
/*module.h*/
#define NB_LINE_MAX 10
#define INFO_MAX 25
struct message3
{
char info_text[NB_LINE_MAX][INFO_MAX]; /*a few info lines.*/
char *error_text; /*only one line for error.*/
int id;
int info_nb_max;
int info_nb;
};
extern struct message3* moduleFcn3(void);
您没有为info_text字符串分配任何内存。你要么必须先使用malloc()
,要么如果你的 C 库支持它(GNU 库支持),使用 asprintf()
而不是 sprintf()
让它分配足够的内存来为你保存整个输出字符串:
for(cpt = 0; cpt < 2; cpt++)
asprintf(&module_text3.info[cpt], "info[%u]", cpt);
不要忘记,您还必须在某个时候再次释放内存。
以下行工作的原因:
module_text3.info_text[0] = "toto[0]";
编译器确保字符串"toto[0]"
存储在内存中的某处,您只需将指针module_text3.info_text[0]
指向该字符串即可。