What's wrong with?

Write your question here.

1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
    char v[][8] { "Hello ", "little ", "friend." };
    char ** p = v;
    std::cout << *p++ << *p++ << *p;
}


source_file.cpp:6:13: error: cannot initialize a variable of type 'char **' with an lvalue of type 'char [3][8]'
    char ** p = v;
            ^   ~
Pointer to pointer is not the same as pointer to multidimensional array!

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main()
{
   char v[][8]{ "Hello ", "little ", "friend." };
   char (*p)[3][8] = &v;
   // both indexes must be specified

   std::cout << (*p)[0] << (*p)[1] << (*p)[2];
   // regular indexes to access values
   std::cin.get();
}
Thank you Grime.
So all multidimensional arrays will internally get handled as one-dimensional arrays, whereby the field-sizes will be used as offsets by the compiler?
Yes c-style arrays are stored sequentially in memory as though they were one dimensional arrays.
std::vector and std::string get around the limitations of C strings and arrays:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <vector>

int main()
{
   std::vector<std::string> strArray { "Hello", "little", "friend." };

   std::vector<std::string> anotherArray = strArray;

   for (const auto& itr : anotherArray)
   {
      std::cout << itr << ' ';
   }
   std::cout << '\n';
}

If you need to access a string's underlying C char array, c_str().
Also, please do not write "p++" more than once per line (or reference p while also doing p++ within the same statement). That is undefined behavior, and even it it weren't, it's very confusing to the reader.
Last edited on
Topic archived. No new replies allowed.