简体   繁体   中英

Char Point Memory Allocation to reference address of C++ String?

I would like to convert an array of Integers 2, 3, 4, 8 5, 7, 9, 12 1, 0, 6, 10

to a string with the entries of that matrix appended in clockwise order “2, 3, 4, 8, 12, 10, 6, 0, 1, 5, 7, 9”.

I have to keep declaration of int * Matrix and char * OutBuffer the way they are

int main()
{
    int matrixArray[rowCount][columnCount] =
    {   {2, 3, 4, 8},
        {5, 7, 9, 12},
        {1, 0, 6, 10}};

    int * matrix;
    string prebuffer;
    char  * outBuffer;

    outBuffer = new (nothrow) char[24];
    matrix = &matrixArray[0][0];

    BuildStringFromMatrix(matrix, rowCount, columnCount, outBuffer);
}

I declare and address all my pointers before passing them in. However, I am not sure if I am going about allocating memory for the outBuffer to store the characters of prebuffer correctly?

void BuildStringFromMatrix(int* Matrix, int NumRows, int NumColumns, char * OutBuffer)
    {
        string prebuffer;
        bool stringLeft = true;
        int i = 0;

        while (stringLeft)
        {
            int clockwiseDir[12] = { 1,1,1,4,1,1,0,4,-4,-1,-1,-1 };

            prebuffer = to_string(Matrix[i]) + ", ";
            OutBuffer = new char [prebuffer.length() + 1];
            cout << prebuffer;
            i += clockwiseDir[i];

            if (i == 6)
            {
                prebuffer = to_string(Matrix[i]) + " ";
                cout << prebuffer;
                stringLeft = false;
            }
        }
    }

**When I do not implement OutBuffer I have no trouble accessing and printing the matrix in clockwise format

But I how would I go about using OutBuffer to reference and print prebuffers contents?? I need numbers to display not unprintable symbols on the ASCII table

Thanks in advance :) **

Firstly, in your loop under BuildStringFromMatrix function you are not using your i value anywhere. Second, matrix = matrixArray should do fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM