结果怪异的数组赋值

array assignment with weird result

问题是将二维数组分配给一维数组

uint8_t Schedules[24][8]={
 {0,1,1,1,1,1,1,0},
 {0,2,2,2,2,2,2,0},
 {0,3,3,3,3,3,3,0},
 ...
 {0,24,24,24,24,24,24,0}
}


for (this_hour=0;this_hour<24;this_hour++){
        for(this_section=1;this_section<7;this_section++)
        {
            buff[this_hour*9+this_section+2]=Schedules[this_hour][this_section];
        }
    }

结果必须是

buff[3..8]=1; /* Pseudocode; means buff[3]=1, buff[4]=1, ..., buff[8]=1 */
buff[9..11]=0;
buff[12..17]=2;
buff[18..20]=0,
...

然而,这是结果

我不知道我哪里错了。我检查了十次循环,没有发现任何错误。我在 keil 5 的 freertos 中为 stm32 ARM 编写。我确保只在 for 循环中访问 buff 而在代码中没有其他地方。它不是堆栈溢出,因为我给堆栈一个很大的数字

这样,数组从0开始,均值

时间表[x][y] x,y 是位置将出现在

下面

x*8+y

0......7 映射自 0,0~0,7

8......15映射自1,0~1,7

16......23映射自2,0~2,7

.......

@kevinmont 你在问题上是对的,我编辑了我的问题并更正了它,是的,你又是对的,我有 3 "0"s of header bytes then 6 "1"s, another 3 "0"s then 6 "2 "s,then 3 "0" 等等。 – 大卫 6 小时前

需要数组大小为24*9+1+2

x*9+y+2

2......9映射自0,0~0,7

11......18映射自1,0~1,7

20......27映射自2,0~2,7

.......

#include <stdio.h>
#include <stdlib.h>
typedef unsigned char uint8_t;
uint8_t Schedules[24][8]={
{0,1,1,1,1,1,1,0},
{0,2,2,2,2,2,2,0},
{0,3,3,3,3,3,3,0},
{0,4,4,4,4,4,4,0},
{0,5,5,5,5,5,5,0},
{0,6,6,6,6,6,6,0},
{0,7,7,7,7,7,7,0},
{0,8,8,8,8,8,8,0},
{0,9,9,9,9,9,9,0},
{0,10,10,10,10,10,10,0},
{0,11,11,11,11,11,11,0},
{0,12,12,12,12,12,12,0},
{0,13,13,13,13,13,13,0},
{0,14,14,14,14,14,14,0},
{0,15,15,15,15,15,15,0},
{0,16,16,16,16,16,16,0},
{0,17,17,17,17,17,17,0},
{0,18,18,18,18,18,18,0},
{0,19,19,19,19,19,19,0},
{0,20,20,20,20,20,20,0},
{0,21,21,21,21,21,21,0},
{0,22,22,22,22,22,22,0},
{0,23,23,23,23,23,23,0},
{0,24,24,24,24,24,24,0}
};

int main(){
    int this_hour,this_section,i;
    uint8_t buff[192]={0};//24*8
    for (this_hour=0;this_hour<24;this_hour++){
        for(this_section=0;this_section<8;this_section++)
        {
            buff[this_hour*8+this_section]=Schedules[this_hour][this_section];
        }
    }
    for(i=0;i<192;i++){

        if(i!=0 && i%8==0){
            printf("\n");
        }
        printf("%d",buff[i]);
    }

    printf("\n------------------------------------\n");


    uint8_t buff2[219]={0};//24*9+1+2
    for (this_hour=0;this_hour<24;this_hour++){
        for(this_section=0;this_section<8;this_section++)
        {
            buff2[this_hour*9+this_section+2]=Schedules[this_hour][this_section];
        }
    }
    for(i=0;i<219;i++){

        if(i!=0 && i%9==0){
            printf("\n");
        }
        printf("%d",buff2[i]);
    }





    return 0;
}

正如 Joshua 在评论中所说,内存有问题,代码是正确的。我创建了一个局部变量,它正在工作。

cuprit 声明错误

extern uint8_t Schedules[24][11];

这个数组的定义是

extern uint8_t Schedules[24][8];

extern声明中数组的第二个参数是wrong.so内存中的代码,调试时看不到