我在訪問我的結構之一中的 char ** 時遇到問題。
uint64_t id;
struct timing timing;
//command *command;
uint32_t argc;
char ** argv;
} taskR;
我正確地存盤了結構中的所有內容,但是當從檔案中讀取它時,我無法訪問 argv 部分而沒有“核心轉儲”警報(其他引數作業得很好)
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
大家新年快樂:) ty 的答案!
uj5u.com熱心網友回復:
它永遠不會奏效。您只讀取指標的值,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,%u\n", t -> id, t -> timing, t -> argc);
for(unsigned i = 0; i < t -> argc; i )
{
fprintf(fo, "%s\n", 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,%u\n", &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;
}
它需要更多的錯誤檢查,但為了簡單起見,我跳過了它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/402625.html
標籤:
