如何在数组中存储地址 - 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] = '[=10=]';                //add [=10=] 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] = '[=11=]';
                array[j] = &(str[i]) + sizeof(char);
                j++;
            }
            else{
                str[i] = input[i];
            }
        }
    }

    void output(int i){
        buffer = array[i];
        cout<<buffer;
    }
};

感谢您的帮助! :)

实际问题的答案:

char ** array = new (char *)[10];

您可能应该做的是:

std::vector<std::string> array;

最好的方法是为此使用标准容器 (std::vector<std::string>)。无论如何,如果您确实需要以 C 方式使用它:

这一行:

array[j] = &(str[i]);

您正在存储字符串的第 个字符的地址。如果要存储指向整个字符串的指针,请使用:

array[j] = str;

请注意,您的代码中还有许多其他错误。 例如,您不应该为此使用固定大小的数组,因为如果您的文本中有更多行,您将面临未定义行为的风险。

顺便说一句。 MyClass 是一个函数,而不是 class。

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] = '[=10=]';              //add [=10=] 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;
};