代码之家  ›  专栏  ›  技术社区  ›  user8235882

未在操作系统C中执行的for循环

  •  4
  • user8235882  · 技术社区  · 8 年前

    我在执行for循环时遇到问题,我创建了一个包含定义值的静态表,然后我将表作为函数中的参数传递给process。

    #define ID_01 0x0000
    #define ID_02 0x0001
    #define ID_03 0x0002
    #define ID_04 0x0003
    #define ID_05 0x0004
    #define ID_06 0x0005
    #define ID_07 0x0006
    #define ID_08 0x0007
    #define ID_09 0x0008
    /*...
    */
    #define ID_LAST 0xFFFF
    static char table[]={
    ID_01, ID_02 ,ID_03, ID_04, .... , ID_LAST}
    
    void process( char *table){
    
        int LastId=0; 
        char *Command; 
    
        for ( Command=table; LastId==0 ; Command++){
            switch(Command) 
            {
                case ID_01: 
                    do_stuff01();
                    break;
                case ID_02: 
                    do_stuff02();
                    break; 
                ...
    
                case ID_LAST: 
                    LastId=1;
                    break;
                default: 
                     break;
              } 
        }
    }
    

    但当我将for循环更改为:

    for(i=0;i<10;i++)
    

    所有信息都打印出来了。但我必须以我最初的方式处理。

    2 回复  |  直到 8 年前
        1
  •  5
  •   unalignedmemoryaccess    8 年前

    现在您正在使用 switch (Command) 哪里 Command 保留地址od table

    改变 switch

    switch (*Command) { //Use value at pointed Command.
    
    }
    

    *Command 你取消了引用 char

    static char table[] = {ID_01, ID_02 ,ID_03, ID_04, .... , ID_LAST}
    

    缩写为16位值

    static unsigned short table[]={ID_01, ID_02 ,ID_03, ID_04, .... , ID_LAST}
    

    process 要接受的函数 unsigned short

    void process( const unsigned short *table) { //Unsigned short
        int LastId = 0; 
        unsigned short *Command;  //Unsigned short
    
        for ( Command=table; LastId==0 ; Command++){
            switch(*Command) { //Added star
                //...
            }
        }
        //...
    

    过程 代码收件人:

    void process(const unsigned short *table, size_t tableLen) {
        while (tableLen--) {
            switch (*table) {
                case ID_1: /* Do stuff */ break;
            }
            table++; //Increase pointer to next ID element
        }
    }
    
    //Usage then like this:
    static unsigned short table[] = {ID_1, ID_2, ID_3, ..., ID_n};
    //Put pointer and length of table
    process(table, sizeof(table)/sizeof(table[0]));
    
        2
  •  1
  •   mattn    8 年前

    #include <stdio.h>
    
    #define ID_01 0x0000
    #define ID_02 0x0001
    /* ... */
    #define ID_LAST 0xFFFF
    
    typedef void (*func)();
    
    typedef struct {
      char n;
      func f;
    } fmap;
    
    void do_something01() { }
    void do_something02() { }
    /* ... */
    
    static fmap fmaps[] = {
      {ID_01, do_something01},
      {ID_02, do_something02},
      /* ... */
      {ID_LAST, NULL},
    };