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] = '\0'; //add \0 Terminator for char[]
array[j] = &(str[i]); //store address of sentence beginning in array
j++;
}
else{
str[i] = input[i];
}
}
}
如何将地址存储到数组中。所以我可以通过数字获取句子的起始地址。我创建了一个解决方案,其中包含一个将我的句子存储为 char* 对象的 vector 。但是必须有一种不用 vector 的方法吗?!
编辑:
这是我的解决方案。
#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] = '\0';
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]);
您正在存储字符串的第 第 个字符的地址。如果要存储指向整个字符串的指针,请使用:
array[j] = str;
请注意,您的代码中还有许多其他错误。 例如,您不应该为此使用固定大小的数组,因为如果您的文本中有更多行,您将面临未定义行为的风险。
顺便说一句。 MyClass
是函数,不是类。
关于c++ - 如何在数组中存储地址 - C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28452986/