如何在数组中存储地址 - C++

How to store adresses in an array - C++?

本文关键字:地址 C++ 存储 数组      更新时间:2023-10-16
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;
};