【问题标题】:Change the address of a pointer更改指针的地址
【发布时间】:2020-03-19 19:42:36
【问题描述】:

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

【问题讨论】:

  • 那么你想要bufferA []数组的第一个元素的内存地址吗?您需要哪种语言?
  • 我在用c写,我想知道如何设置指针的地址,比如 *ptr=&(0x1702) 所以它指向第一个元素,然后以某种方式改变地址 *ptr=&(0x1702 + 2) 所以它指向第二个元素
  • 你想太多了。 ptr = &bufferA[0];, ptr = &bufferA[1];, ...
  • 你可以这样做ptr++;

标签: c arrays pointers storage dma


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    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)
    

    【讨论】:

      猜你喜欢
      • 2013-07-12
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 2021-04-08
      相关资源
      最近更新 更多