通过循环打印数组元素时指向较旧地址的指针

时间:2020-03-19 15:45:13

标签: c function pointers multidimensional-array memory-address

我想通过另一个用户定义的函数读取main函数中定义的数组元素。该数组是2D数组,它正确显示了前三个元素,但是在下一个循环开始时,该指针指向的地址比预期的地址落后2个步。为什么? 这是调用问题所在的frame()函数的主要函数:

void main(){
    char dec,player[2][20];
    int i,counter=0,palo,winner=0;
    for(i=0;i<2;i++){
        printf("Enter Player%d's name: ",(i+1));
        scanf("%s",player[i]);                  //ASK PLAYER NAME
    }
    startAgain:                             //GAME RESTART POINT
    system("cls");
    palo=0;
    char spot[][3]={"123","456","789"};

    //------------------MAIN GAME AREA-------------------------------
    for(counter=0;counter<9;counter++,palo++){
        frame(*spot);
        read(&palo,*spot,*player);
        palo %=2;
    }
}

这是frame()函数:

void frame(char *count){
    int i,j;
    printf("\t\t\t");
    line(24);
    for (i = 0; i < 3; i++){
        printf("\t\t\t");
        for (j = 0; j < 3; j++){
            printf("|   %c   ",(*(count+i)+j));
        }
        printf("|\n\t\t\t");
        line(24);
    }
}

预期的输出是:

1        2       3
4        5       6
7        8       9

显示内容:

1        2       3
2        3       4
3        4       5

1 个答案:

答案 0 :(得分:0)

使您自己和他人的生活更轻松,请使用普通的数组索引而不是指针算术。

class MyThread
{
    private Thread worker = new Thread(MyFunc);
    private BlockingCollection<Action> stuff = new BlockingCollection<Action>();

    public MyThread()
    {
        worker.Start();
    }

    void MyFunc()
    {
        foreach (var todo in stuff.GetConsumingEnumerable())
        {
           try
           {
               todo();
           }
           catch(Exception ex)
           {
              // Something went wrong in todo()
           }
        }
        stuff.Dispose(); // should be disposed!
    }

    public void Shutdown()
    {
         stuff.CompleteAdding(); // No more adding, but will continue to serve until empty.
    }

    public void Add( Action stuffTodo )
    {
          stuff.Add(stuffTodo); // Will throw after Shutdown is called
    }
}
相关问题