#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SUB_COMMANDS 5
#define MAX_ARGS 10
struct SubCommand
{
char *line;
char *argv[MAX_ARGS];
};
struct Command
{
struct SubCommand sub_commands[MAX_SUB_COMMANDS];
int num_sub_commands;
};
void ReadCommand(char *line, struct Command **command);
void PrintCommand(struct Command **command);
void read_args(char *in, char *argv[MAX_ARGS], int size);
void print_args(char *argv[MAX_ARGS]);
int main()
{
char s[200];
printf("Enter Command:");
fgets(s,200,stdin);
s[strlen(s)-1]='\0';
struct Command *command;
ReadCommand(s,&command);
PrintCommand(&command);
}
void ReadCommand(char *line, struct Command **command)
{
const char *delim ="|";
const char *k;
char *copy;
char *l;
int i=0;
(*command)->num_sub_commands=0;
k=strtok(line,delim);
while(k!=NULL)
{
l=strdup(k);
(*command)->sub_commands[i].line=l;
printf("(*command)->sub_commands[%d].line=%s,l=%s\n",i,(*command)->sub_commands[i].line,l);
i++;
printf("%d iteration\n",i);
(*command)->num_sub_commands++;
printf("%d number of subcommands\n",(*command)->num_sub_commands);
k=strtok(NULL,delim);
}
(*command)->sub_commands[i].line=NULL;
for(i=0;(*command)->sub_commands[i].line!=NULL;i++)
{
copy=strdup((*command)->sub_commands[i].line);
read_args(copy,(*command)->sub_commands[i].argv,MAX_ARGS);
}
}
void read_args(char *in, char *argv[MAX_ARGS], int size)
{
const char *del =" ";
int i=0;
const char *k1;
char *l1;
k1=strtok(in,del);
while(k1!=NULL)
{
l1=strdup(k1);
argv[i]=l1;
//printf("argv[%d]=%s\n",i,argv[i]);
i++;
//printf("k1=%s\n",k1);
//printf("l1=%s\n",l1);
k1=strtok(NULL,del);
}
argv[i]=NULL;
}
void PrintCommand(struct Command **command)
{
int i;
for(i=0;(*command)->sub_commands[i].line!=NULL;i++)
{
printf("subcommand[%d]='%s' \n",i,(*command)->sub_commands[i].line);
print_args((*command)->sub_commands[i].argv);
}
}
void print_args(char *argv[MAX_ARGS])
{
int i;
for(i=0;argv[i]!=NULL;i++)
{
printf("argv[%d]='%s' \n",i,argv[i]);
}
}
我遇到段错误,不知道为什么?任何人都可以帮忙吗? 我在 devc++ ide 中运行时遇到段错误,当我在带有优化标志 O0 的 shell 上运行代码时,它工作正常。
最佳答案
我在您的代码中没有看到任何 malloc(以及任何 free)。
在你的主要部分你可以这样做:
struct Command command; //I don't understand why you are using pointers here
ReadCommand(s,command);
PrintCommand(command);
您可以更改:
void ReadCommand(char *line, struct Command **command);
void PrintCommand(struct Command **command);
与:
void ReadCommand(char *line, struct Command *command);
void PrintCommand(struct Command *command);
例如 PrintCommand 可以是:
void PrintCommand(struct Command *command)
{
int i;
for(i=0;command->sub_commands[i].line!=NULL;i++)
{
printf("subcommand[%d]='%s' \n",i,command->sub_commands[i].line);
print_args(command->sub_commands[i].argv);
}
}
当您使用完 SubCommand
结构体的 line
和 argv
时,还请记住使用 free
。
关于使用结构体的 C 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35261706/