如何在数组中存储地址 - C++
How to store adresses in an array - C++?
My Code example:
char* array = new char[10];
char* str;
int j = 0;
MyClass(char* input){ //input = sentence columns terminated by 'n'
str = new char[strlen(input)];
for(int i=0; i<strlen(input); i++){
if (input[i] == 'n'){ //look for end of line
str[i] = ' '; //add Terminator for char[]
array[j] = &(str[i]); //store address of sentence beginning in array
j++;
}
else{
str[i] = input[i];
}
}
}
如何将地址存储到数组中。所以我可以通过数字获得句子的开头地址。我创建了一个解决方案,其中向量将我的句子存储为 char* 对象。但是一定有没有矢量的方法吗?!
编辑:
这是我的解决方案。
#include <iostream>
using namespace std;
class Pointer{
public:
char** array = new char*[10];
char* str;
char* buffer;
int j = 1;
Pointer(char* input){
str = new char[strlen(input)];
array[0] = str;
for (int i = 0; i < strlen(input); i++){
if (input[i] == 'n'){
str[i] = ' ';
array[j] = &(str[i]) + sizeof(char);
j++;
}
else{
str[i] = input[i];
}
}
}
void output(int i){
buffer = array[i];
cout<<buffer;
}
};
感谢您的帮助! :)
最好的方法是为此使用 std 容器 ( std::vector<std::string>
(。无论如何,如果你确实需要用 C 方式:
在这一行中:
array[j] = &(str[i]);
您正在存储字符串的第 i 个字符的地址。如果要存储指向整个字符串的指针,请使用:
array[j] = str;
请注意,您的代码中还有许多其他错误。例如,您不应该为此使用恒定大小数组,因为如果您的文本中有更多行,您将面临未定义的行为。
顺便说一句。 MyClass
是一个函数,而不是一个类。
实际问题的答案:
char ** array = new (char *)[10];
您可能应该做什么:
std::vector<std::string> array;
char* array[10]
char* str;
int j = 0;
MyClass(char* input){ //input = sentence columns terminated by 'n'
str = new char[strlen(input)];
for(int i=0; i<strlen(input); i++){
if (input[i] == 'n'){ //look for end of line
str[i] = ' '; //add Terminator for char[]
array[j] = str; //store address of sentence beginning in array
// or you can use
// array[j] = &(str[0]);
j++;
}
else{
str[i] = input[i];
}
}
}
希望对您有所帮助!
class Pointer{
public:
Pointer(std::string input){
addresses = split(input, 'n', addresses);
}
void output(int i){
std::cout << addresses.at(i);
}
private:
std::vector<std::string> addresses;
};
相关文章:
- 将数组的地址分配给变量并删除
- 空基优化子对象的地址
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 如何在c++程序中找到函数的地址
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 被解释为低级别const的const对象的地址
- 将地址分配给本地指针后,公共对象的变量将消失
- 为什么我在leetcode上收到AddressSanitizer:地址0x602000000058上的堆缓冲区溢出错误
- 内联程序集printf将整数解释为地址
- 为什么指针不写入类的地址?
- 如何在C++中获取该对象的类声明中对象的地址?
- 通过按地址访问变量
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- 函数名是c中该函数的第一条指令的地址吗
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- ReadProcessMemory() 不适用于像 0x2840C6C68D8 这样的长地址
- CUDA:统一内存和指针地址的更改
- 当我们从/tp地址中添加/减去一个整数时会发生什么
- 如何使用 Boost Asio 在 Android 上获取我的本地 udp IP 地址?