为什么下一个内存短路具有另一个变量的值?

时间:2015-10-11 17:28:38

标签: c arrays pointers

在main方法中,我有以下代码:

int main (void)
{
    unsigned short array[3];
    *array = 65535;
    *(array + 1) = 12453;
    *(array + 2) = 45055;

    int bitposition = 12;

    int bitsperSample = 8;

    unsigned short * pointer_array = & array[0];
    unsigned short result = readSample(pointer_array, bitposition, bitsperSample);


}

我的目的是创建一个3元素短数组,我可以在其中存储3个短语,以便在函数readSample中读取它们。该函数如下,其中的代码用于从先前声明的数组中读取两个短路:

unsigned short readSample( unsigned short * track, int bitpos, int bitsPerSample )
    {
    int res = 1;
    int short_to_read = bitpos / 16; 

    int pos_bit_in_the_short = bitpos % 16; // local position of the bit inside the short_to_read  

    unsigned short found = *(track + short_to_read);
    unsigned short * pointer_to_found  = & found;
    unsigned short copy_found = * pointer_to_found;
    printf("first short to read is %d \n", copy_found);

    unsigned short second_short_to_read = * (pointer_to_found + 1);
    printf("second short to read is %d \n", second_short_to_read);


    return res;
} 

我希望打印程序:

first short to read is 65535
second short to read is 12453

但程序输出:

first short to read is 65535
second short to read is 12

这是错误的,因为读取的第二个短片是取pos_bit_in_the_short = bitpos%16的值,我不知道为什么。

我还尝试打印短路的十六进制地址进行读取,看看它是否正在访问存储器的其他部分,现在位,第二个短路是第一个短路后的2个字节,正如我在数据库中声明数据所预期的那样主要方法。地址是:

0xbfc120f2 for the first short and 
0xbfc120f4 for the second short.

任何人都可能知道为什么会这样?

1 个答案:

答案 0 :(得分:2)

问题在于:

unsigned short found = *(track + short_to_read);
unsigned short * pointer_to_found  = & found;

found是一个局部变量(在readSample中),以下逻辑使用它就好像它是一个数组 - 它不是。