更改指针的地址

时间:2020-03-19 19:42:36

标签: c arrays pointers storage dma

我有一个称为bufferA []的整数数组和一个指向该数组bufferA [0]中第一个整数的指针* ptr。现在,我想将指针更改为指向第二个值bufferA [1]。当我调试代码时,我可以看到该数组中第一个整数的地址为0x1702,现在我想更改指针,使其指向缓冲区A [1]的地址0x1704。 可能有一些方法可以使它不使用指针而只读取Array的值,但是此Array是从ADC模块传递到DMA模块的,而不是仅采用Array(这使得将它们存储在DMA中)无用)我只想取第一个值的地址并将其更改为读取以下值。 我希望这能以某种方式解释我的问题...

2 个答案:

答案 0 :(得分:0)

ptr = ptr + 1;怎么样? (或者在这种情况下等效地为ptr += 1;ptr++;++ptr;?)C编译器知道ptr指向的项目占用了多少字节,因为它的声明的类型,并会自动将指针增加正确的字节数。

答案 1 :(得分:0)

C语言中的数组始终通过引用传递,您没有复制操作就可以将其作为函数的参数传递!(这是初学者C程序员的第一个陷阱)

首先,但简短地阅读一些有关C语言中指针的信息:

int a = 5;    // declares a integer-type of value 5
int* pta;     // declares a pointer-to-integer type
pta = &a      // assigns the **address** of a to pta (e.g. 0x01)
int b = *pta  // assingns the **value** of the address location that pta is pointing to into b
              // (i.e. the contents of memory address 0x01, which is 5)
*pta = 4      // assigns 4 to the content of the memory address that pta is pointing to.

// now b is 5, because we assigned the value of the address that pta was pointing to
// and a is 4, because we changed the value of the address that pta was pointing to
// - which was the address where variable a was stored

变量bufferA本身是指向第一个元素地址的指针。 bufferA + 1为您提供第二个元素的地址,因为数组顺序存储在内存中。

或者,如果您想要更具可读性的格式:

&bufferA[0]  is the same as  bufferA         (address of the first element(e.g 0x11) 
&bufferA[1]  is the same as  bufferA + 1     (address of the second element(e.g 0x12) 
buffer[2]    is the same as  *(buffer + 2)   (value at the address of the third element)
相关问题