我在处理一个结构中的字符**时遇到问题。
uint64_t id;
struct timing timing;
//command *command;
uint32_t argc;
char ** argv;
} taskR;
我正确地将所有内容存储在我的结构中,但当从文件中读取时,我无法访问argv部分;堆芯倾倒";alert(其他参数运行良好(
taskR stp;
uint64_t ip=stp.id;
read(i,&stp,sizeof(struct task));
struct timing ti;
ti=stp.timing;//all good
printf("%s",stp.argv[0]);//core dumped
大家新年快乐:(答案是肯定的!!
它永远不会工作。您只读取指针argv
的值,而不读取分配给它的指针和字符串的引用数组。即使您读取了它,它们在写入时也会引用除原始内存区域之外的其他内存区域。
您将需要序列化它并保存所有底层数据。然后你需要阅读它并重建结构。
示例:
typedef struct
{
unsigned id;
unsigned timing;
//command *command;
unsigned argc;
char ** argv;
} taskR;
char *removeLastLF(char *str)
{
char *wrk = str;
if(str && str)
{
while(*(str + 1)) str++;
if(*str == 'n') *str = 0;
}
return wrk;
}
int mywrite(FILE *fo, taskR *t)
{
fprintf(fo, "%u,%u,%un", t -> id, t -> timing, t -> argc);
for(unsigned i = 0; i < t -> argc; i ++)
{
fprintf(fo, "%sn", t -> argv[i]);
}
return 0;
}
taskR *myread(FILE *fi)
{
char buff[128];
taskR *t = malloc(sizeof(*t));
if(t)
{
fgets(buff, 128, fi);
if(sscanf(buff, "%u,%u,%un", &t -> id, &t -> timing, &t -> argc) == 3)
{
t -> argv = malloc(t -> argc * sizeof(*t -> argv));
for(unsigned i = 0; i < t -> argc; i ++)
{
fgets(buff, 128, fi);
removeLastLF(buff);
t -> argv[i] = malloc(sizeof(**t -> argv) * strlen(buff) + 1);
strcpy(t -> argv[i], buff);
}
}
}
return t;
}
它需要更多的错误检查,但为了简单起见,我跳过了它。