Inicializando un Char*[]


La pregunta está en el título, cómo inicializo un char* [] y le doy valores en C++, gracias.

Author: Romain, 2010-02-10

8 answers

Aunque probablemente esté al tanto, char* [] es una matriz de punteros a caracteres, y supongo que desea almacenar un número de cadenas. Inicializar una matriz de estos punteros es tan simple como:

char ** array = new char *[SIZE];

...o si está asignando memoria en la pila:

char * array[SIZE];

Entonces probablemente querrías llenar el array con un bucle como:

for(unsigned int i = 0; i < SIZE; i++){
    // str is likely to be an array of characters
    array[i] = str;
}

Como se indica en los comentarios de esta respuesta, si está asignando la matriz con new (dynamic allocation) recuerde eliminar su matriz con:

delete[] array;
 18
Author: Stephen Cross,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-10 21:00:16

Dependiendo de lo que quieras inicializar puedes hacer cualquiera de:

char mystr[] = {'h','i',0};
char * myotherstring = "my other string";
char * mythirdstring = "goodbye";

char * myarr[] = {0};
char * myarr[] = {&mystr, myotherstring};
char * myarr[10];
char * myarr[10] = {0};
char * myarr[10] = {&mystr, myotherstring, mythirdstring, 0};

Etc. sucesivamente.

 10
Author: John Weldon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-10 20:30:29

Así:

char* my_c_string;
char* x[] = { "hello", "world", 0, my_c_string };
 7
Author: Max Shawabkeh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-10 20:31:17

He notado una cosa de la que debes tener cuidado... C y C++ han divergido un poco en la sintaxis de inicialización. Como Mark B. señala anteriormente, puede inicializar una matriz de punteros char de esta manera:

const char* messages[] =
{
    "Beginning",
    "Working",
    "Finishing",
    "Done"
};

Pero en C++. como kriss señala, esto le da una advertencia sobre una conversión obsoleta de string a char*. Esto se debe a que C++ asume que querrás usar cadenas para cadenas; -}.

Eso no siempre es cierto. Así que cuando realmente desea inicializar una matriz de char*, I he encontrado que tengo que hacerlo así:

const char* messages[] =
{
    (char*)("Beginning"),
    (char*)("Working"),
    (char*)("Finishing"),
    (char*)("Done")
};

El compilador ahora está contento...

 6
Author: Don Doerner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-23 00:07:22

Si realmente solo desea una matriz de cadenas constantes estilo C (por ejemplo, mensajes indexados):

const char* messages[] =
{
    "Beginning",
    "Working",
    "Finishing",
    "Done"
};

Sin embargo, si está tratando de mantener un contenedor de cadenas de variables en tiempo de ejecución, usar la instalación de C++ std::vector<std::string> hará que el seguimiento de todas las operaciones de memoria sea mucho más fácil.

std::vector<std::string> strings;
std::string my_string("Hello, world.")
strings.push_back("String1");
strings.push_back(my_string);
 2
Author: Mark B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-10 20:38:49

Así:

char p1 = 'A';
char p2 = 'B';
char * t[] = {&p1, &p2};

std::cout << "p1=" << *t[0] << ", p2=" << *t[1] << std::endl;

Pero de alguna manera creo que esa no es la respuesta a la pregunta real...

Si desea una matriz de cadenas C definidas en tiempo de compilación, debe usar una matriz de const char * en su lugar:

const char * t2[] = {"string1", "string2"};

std::cout << "p1=" << t2[0] << ", p2=" << t2[1] << std::endl;

Sin la const mi compilador diría : advertencia: conversión obsoleta de la constante de cadena a 'char*'

 2
Author: kriss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-10 20:46:48

Al igual que cualquier otra matriz:

char *a, *b, *c;
char* cs[] = {a, b, c}; // initialized
cs[0] = b; // assignment
 1
Author: Peter Alexander,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-10 20:30:01
#include <iostream>

int main(int argc, char *argv[])
{
    char **strings = new char *[2]; // create an array of two character pointers
    strings[0] = "hello"; // set the first pointer in the array to "hello"
    strings[1] = "world"; // set the second pointer in the array to "world"

    // loop through the array and print whatever it points to out with a space
    // after it
    for (int i = 0; i < 2; ++i) {
        std::cout << strings[i] << " ";
    }

    std::cout << std::endl;

    return 0;
}
 1
Author: xian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-10 20:38:12