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

jackxiang 2008-12-4 18:24 | |
结构体的定义:


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 <stdio.h>
#include <unistd.h>
#include <string.h>

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;
}

作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:https://jackxiang.com/post/1473/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!

评论列表
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]