0


Can I define pointer to a string array like this?

std::string* str_arr_p[];

Or I need to set the size of the array?

P.S.: Is there any difference between std::string* str_arr_p[n]; and
std::string (*str_arr_p)[n];

2
  • 1
    Recommendation: read about stack and heap memory and about memory allocation. In your case, without any size, how would the computer know which address to give to you? If that address couldn't handle a hundred entries (because after that, the memory is in usage), what should happen? And how should it reserve memory if it has no idea of how much to reserve? Also, in most cases, you should really use a container class like std::vector instead. Commented Apr 19, 2020 at 9:57
  • 1
    And yes, there's a difference. The former declares an array of n pointers to std::string; the latter declares a pointer to an array of n std::string. Commented Apr 19, 2020 at 9:59

2 Answers 2

1

Can I initialize pointer to a string array like this? std::string* str_arr_p[]; Or I need to set the size of the array?

No you can't. Try it and see that you get compilation error.

Is there any difference between std::string* str_arr_p[n]; and std::string (*str_arr_p)[n];

Yes there is. The first is an array of n pointers to std::string, the second is a single pointer to an array of std::string of size n.

Note that both are uninitialized (if not declared as global or static), i.e. both point or hold arbitrary address(es). The first holds n arbitrary addresses that can be initialized separately with a valid address or nullptr for each of the n pointers in the array. The second is a single address that need to be initialized with an address of an std::string array which has the exact size n.

Sign up to request clarification or add additional context in comments.

2 Comments

don't you mean "is a pointer to an array of n std::string ?"
sure, fixed :-)
1
std::string* str_arr_p[n];

is an array of pointers to std::string. std::string (*str_arr_p)[n]; here str_arr_p is a pointer to an array of n std::string

std::string* str_arr_p[]; this is a definition, you don't initialize anything. std::string* str_arr_p[] = new std::string* [x]; heap allocated or std::string* str_arr_p[50]; Stack allocated, this will be destroyed when function ends

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.