更改指针的地址

问题描述 投票:0回答:2

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

c arrays pointers storage dma
2个回答
0
投票

ptr = ptr + 1;如何? (或者等效于ptr += 1;ptr++;++ptr;?)C编译器由于其声明的类型而知道ptr所指向的项占用了多少字节,并将自动递增指针按正确的字节数。


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)
© www.soinside.com 2019 - 2024. All rights reserved.