c++存储数组下一个位置的地址
c++ store address of next position of the array
我有一个数组,我想将下一个数组的地址存储在当前位置。
到目前为止,我有
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(。
相关文章:
- 将数组的地址分配给变量并删除
- 空基优化子对象的地址
- 将值指定给向量(2D)的向量中的某个位置
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 如何在c++程序中找到函数的地址
- 为什么在递增后使用 [] 运算符访问指针数组会返回错误地址的当前内存位置
- 相同地址位置如何给出两个不同的值
- 明确分配或从内存中的特定地址/位置分配或访问值
- 在双链表中,指针不是存储彼此的地址,而是指向相同的位置
- 虚拟内存地址所在的位置
- Vpointer 在 C++ 中的地址和位置
- 如何判断共享库在进程地址空间中的加载位置
- 获取地址在数组2d中的位置
- c++存储数组下一个位置的地址
- 动态数组改变内存地址位置
- PC的IP地址到位置坐标