c++存储数组下一个位置的地址

c++ store address of next position of the array

本文关键字:地址 位置 下一个 存储 数组 c++      更新时间:2023-10-16

我有一个数组,我想将下一个数组的地址存储在当前位置。

到目前为止,我有

char *a = new char[50];
char *free = a;
*a = &(a + 1); //value of a[0] is equal to the address of a[1] 

此外,我正在使用char数组,所以我确信我需要投射一些东西
任何帮助都会很好。

不能在char数组中存储char*。

一个字符等于一个字节。指针的大小(如char*(因您的计算机而异。在我的电脑上,它有8个字节。1个字节无法容纳8个字节。

#include <iostream>
int main()
{
    std::cout << "sizeof(char): " << sizeof(char) << std::endl;
    std::cout << "sizeof(char*): " << sizeof(char*) << std::endl;
    return 0;
}
// Outputs 
// sizeof(char): 1
// sizeof(char*): 8

您也无法将char*强制转换为char以将其放入数组中,因为编译器会对您大喊大叫。

#include <iostream>
int main()
{
    char myArray[10];
    std::cout << (char)&myArray[0];
}
// Compiler error:
// g++ main.cpp -std=gnu++11
// main.cpp: In function ‘int main()’:
// main.cpp:7:34: error: cast from ‘char*’ to ‘char’ loses precision [-fpermissive]

要使其工作,最接近的方法是使用size_t数组。size_t是指针的大小。因此size_t和size_t*中的字节数相等,因此您可以将size_t*放入size_t的数组中。。。铸造后。

#include <iostream>
int main()
{
    size_t myArray[10];
    myArray[0] = reinterpret_cast<size_t>(&myArray[1]);
    std::cout << std::hex << "0x" << myArray[0] << std::endl;
}
// Outputs: 0x7fff4eded5c8

此外,请考虑使用标记[],而不是添加指针。它的可读性更强,而且在引擎盖下也能做同样的事情。a[1]==*(a+1(。