1

I have an assignment to create a block transposition cipher program. A user is to input a phrase of their choice, and the program is to strip the phrase of spaces, punctuation, and make lowercase, before reading its length and creating a two-dimensional array the size of the nearest square that will fit all the chars in the mutated string, and filling in the remaining space with random letters.

Problem is, I'm having issues with creating that square.

I have this so far:

int main()
{
    string input;
    cout << "Please enter message to cipher." << endl;
    getline(cin, input);

    /* do punctuation removal/mutation */

    int strLength = input.length(); //after mutation

    /* need to find the square here before applying sizes and values to arrays */

    char * original = new char[][]; // sizes pending
    char * transposed = new char[][]; // sizes pending

    for (int i = 0; i <= /* size pending */ ; i++)
    {
        for (int j = 0; j <= /* size pending */ ; j++)
        {
            transposed[j][i] = original[i][j];
        }
    }

    /* do more stuff here */
}

any ideas?

(I already have done the mutation portion; tested with alternate code)

1
  • Wouldn't it be char ** original? Commented Nov 9, 2012 at 5:33

3 Answers 3

2

You can't do e.g.

char * original = new char[][];

First of all you are trying to create an array of arrays (or pointer of pointers) and assign it to a single pointer. You need to do it in two steps:

  1. Allocate the "outer" array:

    char **original = new char* [size];
    
  2. Allocate the "inner" strings:

    for (int i = 0; i < size; i++)
        original[i] = new char [other_size];
    

However I would highly recommend against using that! Instead you should be using std::vector instead of "arrays" allocated on the heap, and if the contents are strings then use std::string:

std::vector< std::vector< std::string > > original;
Sign up to request clarification or add additional context in comments.

Comments

0

You can take the square root of the length, round down to an integer, and add one to get the new length.

int len = (int)(sqrt(strLength) + 1e-9) + 1;

You'd then malloc the square using len and fill as you normally would.

Comments

0

I believe you do not need the "new" to create your storage. Following code should just do the job:

char buf[size][size]; // size is a variable
... // populate your buf

char tmp;
for(int i = 0; i < size; i++) {
  for(int j = 0; j < i; j++) {
    tmp = buf[i][j];
    buf[i][j] = buf[j][i];
    buf[j][i] = tmp;
  }
}

This does the transpose in place. You don't need another array to store the char's.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.