Dynamic String Array not Compiling

Hi,

I'm not understanding why my dynamic array won't compile.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    int square = 1;
    int k;
 
    for (int i = length; i < length*length; i++){
        for (int j = 1; j < length*length; j++){
            
            if (i / j == j){
                square = i;
                k = j;
                break;
            }

        }

        if (square != 1){
            break;
        }

    }
    
    string* arr; 
    arr = new string[k][k];


I'm trying to get better working with dynamic arrays, but I'm at a roadblock with this.

Thank you.

***edit***
Also, if anyone has a better way of finding the smallest square root greater than number n than a loop with not one, but two forbidden breaks, I'd welcome a better solution.
*********
Last edited on
Maybe something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>

template<typename T>
T** make_2d_array(size_t rows, size_t columns)
{
    auto a = new T*[rows];            // array of row pointers
    a[0] = new T[rows * columns];     // all T data as a single block
    for (size_t i = 1; i < rows; ++i) // init row pointers
        a[i] = a[i - 1] + columns;
    return a;
}

int main()
{
    size_t length = 0;
    std::cout << "Length: ";
    std::cin >> length;

    double sqr = std::ceil(std::sqrt(length));
    length = size_t(sqr * sqr);

    auto a = make_2d_array<std::string>(length, length);

    for (size_t r = 0; r < length; ++r)
        for (size_t c = 0; c < length; ++c)
            a[r][c] = std::to_string(r) + ':' + std::to_string(c);

    for (size_t r = 0; r < length; ++r) {
        for (size_t c = 0; c < length; ++c)
            std::cout << std::setw(5) << a[r][c] << ' ';
        std::cout << '\n';
    }

    delete[] a[0]; // delete data block
    delete[] a;    // delete row pointers
}

Last edited on
Do all dynamic 2d arrays have to be an array of templated objects?
Nope.
Last edited on
>> dutch

I got it!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char** a = new char*[k];
    
    for(int i = 0; i < k; ++i){
        a[i] = new char[k];
    }
    
    for (int j = 0; j < k; j++){
        a[k-1][j] = '*';
    }
    
    int i=0;
    for(int row=0; row < k-1; row++){
        for(int column=0;column < k; column++, i++){
            a[row][column] = x[i];
        }
    }


Thanks for the sample code.
Registered users can post here. Sign in or register to post.