How to initialize a string vector within a struct?

Asked

Viewed 225 times

-1

I need to start a list with names of people at the beginning of my program and I am trying to initialize the names in a string within my struct, that way:

char* nomes[100] = {"gabriel" , "vanessa"};

but I’m getting this error: "Too many initializer values", I tried to initialize outside the struct too but without success.

2 answers

2

I didn’t see any problem, it could be the compiler configuration you are using.

But if you are using C++ then use the type string and not a array of char. Better yet, use a vector to store the strings:

#include <string>
#include <vector>
using namespace std;

int main() {
    char *nomes[100] = { "gabriel" , "vanessa" };
    string aNomes[] = { "gabriel" , "vanessa" };
    vector<string> vNomes = { "gabriel" , "vanessa" };
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

If you don’t do this and you don’t have a good reason you’re just programming in C in the C++ compiler and probably learning wrong.

1


When I tried to compile this code I received the following error: ISO C++11 does not allow Conversion from string literal to 'char *'.

These values { "Abriel", "Valencian" } create a matrix matrix of type const char*.

The pointer names need to be of type const char* to point to that matrix.

When the program is running, each element is copied to a char[100] matrix, which allows the modification of each element separately.

#include <iostream>

int main()
{
  const char* nomes[100] = { "gabriel", "vanessa" };

  std::cout << nomes[0] << '\n';
  std::cout << nomes[1] << '\n';

  nomes[0] = "vanessa";
  nomes[1] = "gabriel";

  std::cout << nomes[0] << '\n';
  std::cout << nomes[1] << '\n';

  return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.