-1

How do you create a pointer to an array?

std::string string_array[5 /*<-an arbitrary length determined by a function*/];
std::string** array_pointer = &string_array;

I'll compile this on a Windows 7, 64-bit using MinGW version 4.8.1, and get this error:

main.cpp:116:28: error: cannot convert 'std::string (*)[(((sizetype)<anonymous>) + 1)] {aka std::basic_string<char> (*)[(((sizetype)<anonymous>) + 1)]}' to std::string** {aka std::basic_string<char>**}' in initialization string** array_pointer = &string_array;

From what I can infer from this wall of text, it doesn't seem to want to set array_pointer equal to the address of string_array. Yet as I understand from this link this should compile, because an array is essentially a pointer, so I should create a pointer pointer and point it to the address of my other pointer(my array), correct?

  • 1
    Use a vector of strings to avoid this rubbish. `std::vector *` easy peasy – Neil Kirk Jun 29 '14 at 01:57
  • 3
    "because an array is essentially a pointer" unfortunately, not true. – Neil Kirk Jun 29 '14 at 01:58
  • **-1** not the real code. the error message says the real code is using a variable length array, which is a C99 feature, offered as a C++ language extension by g++. the presented code has a fixed size array. it is claimed "this", the presented code, is compiled and produced the error message. not so. – Cheers and hth. - Alf Jun 29 '14 at 02:49
  • Thanks to @NeilKirk, that solution worked much better than what I was trying. – watermelonduck Jun 29 '14 at 20:53

1 Answers1

2

You just need one *, i.e.,

 std::string* array_pointer = string_array;

Arrays decay to pointers so you don't need the ampersand at all. Their relationship with pointers can be sometimes confusing, but in a lot of places (like here) their are just interchangeable.

You can also do something that is actually a pointer to an array, but I don't think it is what you want in this case. The syntax would be

 std::string (*array_pointer)[5] = &string_array;

And here you need to know the length. The actual machine language code generated would be the same, but the compiler will do some more restrictive type-checking for you. I.e., if you replace the 5 with 4 above, you'll get a compile error.

toth
  • 2,519
  • 1
  • 15
  • 23
  • Thanks to @toth and [this](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c?rq=1) for clearing up how arrays work, this helped a lot. – watermelonduck Jun 29 '14 at 20:50
  • @chris, yes, that's what I meant, thanks, edited to fix. – toth Jun 30 '14 at 13:59