结构体指针的初始化问题及命令行输入的参数传递到主函数!(小寿原创)

3136阅读 0评论2008-04-11 xiaoshou330
分类:C/C++

结构体的定义:

typedef struct
{   
     char ip[30];    
     char usb[30];
}xiaoshou_cmd;


结构体的初始化:
    

xiaoshou_cmd *conf,tem;   
strcpy(tem.ip,"xiaoshou");    
printf("ip= %s\n",tem.ip);     strcpy(tem.usb,"xiaoshou");    
printf("ip= %s\n",tem.usb);

结构体的指针初始化:
xiaoshou_cmd *conf,tem;   
conf=&tem;         //结构体指针必须实例化,不然会出现莫名的错误! strcpy(conf->ip,"xiaoshou");    
printf("ip= %s\n",conf->ip);
strcpy(conf->usb,"xiaoshou"); 
printf("ip= %s\n",conf->usb);

测试程序:
/××××××××将命令行输入的参数传递到主函数中×××××××××××××××××/
#include
#include
#include

typedef struct
{    char ip[30];
      char usb[30];
      int help_flag;
}xiaoshou_cmd;

xiaoshou_cmd * get_cmd_conf1(int argc,char  *argv[]);
int main(int argc,char  *argv[])
{
    printf("argc= %d \n",argc);
    xiaoshou_cmd *conf,tem;
    conf=&tem;
    opterr = 0;
    conf=get_cmd_conf1(argc,argv);
    if (conf->help_flag==1)
    {
        printf("-i:   server ip!\n");
        printf("-u:   device usb!\n");
        printf("-h:    help!\n");
    }
    else
    {
        printf("ip= %s\n",conf->ip);
        printf("usb= %s\n",conf->usb);
    }

    return 0;
}

xiaoshou_cmd * get_cmd_conf1(int argc,char  *argv[])
{
    int result;
    xiaoshou_cmd *res;
    opterr = 0;
    while((result=getopt(argc,argv,"i:u:h"))!=-1)
    {
        switch(result)
        {
            case 'u':
                strcpy(res->usb,optarg);
                break;
            case 'i':
                strcpy(res->ip,optarg);
                break;
            case 'h':
                res->help_flag=1;
                break;
        }
    }
    return res;
}


上一篇:Linux程序设计——用getopt处理命令行参数(小寿转载)
下一篇: VC #pragma pack() 和sizeof (小寿转载)