How can we determine 2D array's column count automatically?

Is it possible to write kinda like "strlen(myArray [1])" inside of right square brackets instead of "200". (In the code example)

Code Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

int main ()
{
    char myArray [][200] {
    
        {"This is a test text about c style 
            strings."},
        {"How can we determine the longest 
            column and type it inide of the 
            column square brackets which is on 
            the right."}
    
    };
    
    cout << *(myArray + 1);

    return 0;
}
No.

myArray is technically an array of two elements, where each element is an array of 200 char elements.

Array elements are stored right next to each other in memory and all elements need to have the same size. If they had different sizes the array indexing would not be as efficient.

So that is why you need to specify all but the first dimension of the array, so that the size of the elements are known.

There are of course ways around it. You could for example store an array of pointers.
1
2
3
char str1[] = "This is a test...";
char str2[] = "How can we det...";
char* myArray[] { str1, str2 };
(accessing the elements is done the same way as before)

If you're not going to modify the strings you can store pointers to the string literals directly. If you do this you have to mark the pointers as const.
 
const char* myArray[] { "This is a test...", "How can we det..." };

But in C++ there is a library type that is designed for storing strings that you might want to use. It's called std::string and becomes available if you include the <string> header.
 
std::string myArray[] { "This is a test...", "How can we det..." };
(if you use using namespace std; you don't need the std:: in front of string)

At some point you will also learn about std::vector which is an alternative to arrays that has several advantages. It can be resized, it doesn't lose information about its size when being passed to functions, etc. so if I were to write something like this it would probably look more like the following:
 
std::vector<std::string> myStrings { "This is a test...", "How can we det..." };
Last edited on
The dimensions of a c-style array must be known at compile time. Same as std::array. Why not use std::string? Then you can do:

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

int main() {
    const std::string myArray[] {"This is a test text about c style strings.",
            "How can we determine the longest \
            column and type it inside of the\
            column square brackets which is on\
            the right."};

    std::cout << myArray[1] << '\n';
}



Thanks again both of you guys. I'm learning it from udemy course and school classes. I already learned about some vectors and strings but our teacher wants C-style things nowadays.
Topic archived. No new replies allowed.