gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:53:19 25 4
gpt4 key购买 nike

在主方法中我有以下代码:

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 中读取它们。该函数如下,内部代码旨在从先前声明的数组中读取两个short:

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,我不知道为什么。

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

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

任何人都可能知道为什么会发生这种情况?

最佳答案

问题出在这里:

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

found 是一个局部变量(在 readSample 中),以下逻辑将它用作数组,但事实并非如此。

关于c - 为什么内存中的下一个短路具有另一个变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33067959/

25 4 0
文章推荐: c - 分配字符串时指针存储什么地址?
文章推荐: c# - C#中的文件操作
文章推荐: c# - 无法将默认比较器作为 IComparer