使用char **和struct的错误(null)

时间:2018-06-06 12:55:43

标签: c

我试图在一个结构中保存一个char **,我的代码是:

job * proceso = new_job(123,args[0],args,BACKGROUND);
printf("%s",(proceso->commando)[0]);

其中args是char **;

和apperar(null); 结构是:

job * new_job(pid_t pid, const char * command,char ** commando, enum job_state state){
    job * aux;
    aux=(job *) malloc(sizeof(job));
    aux->pgid=pid;
    aux->state=state;
    aux->command=strdup(command);
    aux->commando=malloc(1000);
    aux->next=NULL;
    return aux;}


typedef struct job_{
   pid_t pgid; /* group id = process lider id */
   char * command; /* program name */
   char ** commando;
   enum job_state state;
   struct job_ *next; /* next job in the list */} job;


job * new_job(pid_t pid, const char * command,char ** commando, enum job_state state);

char** com;
#define new_list(name)           new_job(0,name,com,FOREGROUND)  // name must be const char *

我不知道错误;任何人都可以帮助我?

1 个答案:

答案 0 :(得分:0)

要复制char **变量,您需要知道数组中有多少指针。就像main中的argc一样,argv会告诉您// Added num_commando parameter job * new_job(pid_t pid, const char * command, char ** commando, size_t num_commando, enum job_state state) { job * aux; aux=(job *) malloc(sizeof(job)); aux->pgid=pid; aux->state=state; aux->command=strdup(command); // Create array of pointers aux->commando = malloc(sizeof(char *) * num_commando); // or sizeof(*aux->commando) // Duplicate every string for (size_t i = 0; i < num_commando; i++) { aux->commando[i] = strdup(commando[i]); } aux->next=NULL; return aux; } 中有多少指针。添加该数据后,您可以:

num_commando

您还应该将free()参数添加到结构中,以便知道var configuration = new Configuration(); var migrator = new DbMigrator(configuration); migrator.Update(); 的字符串数。