Thread: Matrix class(strings but no string header allowed)

  1. #1
    Registered User
    Join Date
    Sep 2013
    Posts
    1

    Question Matrix class(strings but no string header allowed)

    Hello everbody,

    i am IT student and had a C++/C (oral + paper) exam today. One of the tasks was to write a 2D-Matrix(as the question said) class with following restrictions:

    - No <string> header is allowed
    - Only Dtor needs to be implemented
    - No templates
    - Following should be possible:
    Code:
    std::cout << mat1 + mat2 + "some randome string";
    mat1 += mat2;
    So i did the following:
    In Matrix.h i wrote:
    Code:
    Class Matrix{
       int rows, cols;
       char *arr[][];
    
    public:
       Matrix(int r = 0; int c = 0);
       virtual ~Matrix();
       Matrix operator+(const Matrix& rarg);
       Matrix& operator+=(const Matrix& rarg);
       Matrix operator+=(const char* str);
       friend ostream& operator<<(ostream& out, const Matrix& mat);
    };
    In the source file i wrote(only Dtor here since i have question about it):
    Code:
    Matrix::~Matrix(){
       if(arr){
          for(int i = 0; i < rows; i++){
             delete [] arr[i];
          }
          delete [] arr;
       }
    }

    Now..this destructor made me loose some points since the Prof. said that it is not correct. The corrected version was:
    Code:
    Matrix::~Matrix(){
       if(arr){
          for(int i = 0; i < rows; i++){
             for(int j = 0; j < cols; j++){
                delete [] arr[i][j];
             }
             delete [] arr[i];
          }
          delete [] arr;
       }
    }
    Now, i agree on that error i made, but it is only in case we use the "new" keyword to reserve place dynamically for each string(for each char*). So this raised the question in my head about:

    Since the following is allowed in C++
    Code:
        char* str1 = "hello";
        char* str2 = "you";
        arr[1][3] = str1;//arr[1][3] was initialized to "_" without new keyword
        arr[6][0] = str2;//arr[6][0] was initialized to "_" without new keyword
    why would someone use the new keyword..i mean like this:

    Code:
        arr[1][3] = new char*[sizeof("sometext1")+1];
        arr[1][3] = "sometext1";
        arr[6][0] = new char*[sizeof("sometext2")+1];
        arr[6][0] = "sometextw";
    Can somebody please explain to me what is happening internally in C++ in both the cases(with and without new keyword)?

    Thanks.

  2. #2
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Normally an array of pointers is considered to be the equivalent of a 2d matrix: char *ap[]; as opposed a matrix of pointers: char *mp[][]; . The array of pointers would also be consistent with the usage of: mat1 + mat2 + "some random string", assuming that a + b results in a new matrix with an array of pointers to a new copy of all the strings in a and b.
    Last edited by rcgldr; 09-27-2013 at 05:52 PM.

  3. #3
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by CppNewb View Post
    Hello everbody,

    i am IT student and had a C++/C (oral + paper) exam today. One of the tasks was to write a 2D-Matrix(as the question said) class with following restrictions:

    - No <string> header is allowed
    - Only Dtor needs to be implemented
    - No templates
    - Following should be possible:
    Code:
    std::cout << mat1 + mat2 + "some randome string";
    mat1 += mat2;
    So i did the following:
    In Matrix.h i wrote:
    Code:
    Class Matrix{
       int rows, cols;
       char *arr[][];
    
    public:
       Matrix(int r = 0; int c = 0);
       virtual ~Matrix();
       Matrix operator+(const Matrix& rarg);
       Matrix& operator+=(const Matrix& rarg);
       Matrix operator+=(const char* str);
       friend ostream& operator<<(ostream& out, const Matrix& mat);
    };
    In the source file i wrote(only Dtor here since i have question about it):
    Code:
    Matrix::~Matrix(){
       if(arr){
          for(int i = 0; i < rows; i++){
             delete [] arr[i];
          }
          delete [] arr;
       }
    }

    Now..this destructor made me loose some points since the Prof. said that it is not correct. The corrected version was:
    Code:
    Matrix::~Matrix(){
       if(arr){
          for(int i = 0; i < rows; i++){
             for(int j = 0; j < cols; j++){
                delete [] arr[i][j];
             }
             delete [] arr[i];
          }
          delete [] arr;
       }
    }
    Now, i agree on that error i made, but it is only in case we use the "new" keyword to reserve place dynamically for each string(for each char*). So this raised the question in my head about:

    Since the following is allowed in C++
    Code:
        char* str1 = "hello";
        char* str2 = "you";
        arr[1][3] = str1;//arr[1][3] was initialized to "_" without new keyword
        arr[6][0] = str2;//arr[6][0] was initialized to "_" without new keyword
    why would someone use the new keyword..i mean like this:

    Code:
        arr[1][3] = new char*[sizeof("sometext1")+1];
        arr[1][3] = "sometext1";
        arr[6][0] = new char*[sizeof("sometext2")+1];
        arr[6][0] = "sometextw";
    Can somebody please explain to me what is happening internally in C++ in both the cases(with and without new keyword)?

    Thanks.
    In the latter case, you've simply got a memory leak. That is, you assign the result of "new" to the index and then straightaway reassign it to a constant literal, forever losing track of the allocated memory. Instead, you should use strncpy, memcpy, or the like to copy the data into the newly allocated buffer. Either way, you simply can't assign the index to a string literal because later your code will be "delete[]"ing it, and doing so on a chunk of memory not allocated by "new" is a very bad thing! Also, FWIF, those sorts of raw allocations are a really sloppy practice - I strongly recommend that you (and perhaps your instructor as well) learn about RAII...
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    >>- No <string> header is allowed
    I suggest that your instructor learn C++ properly and don't force students to code C++ the C way.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    - No <string> header is allowed
    Screw the rules. I would have written my own string class with the functions I needed as opposed to not having one, and then, I would have made the matrix class.

  6. #6
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by whiteflags View Post
    Screw the rules. I would have written my own string class with the functions I needed as opposed to not having one, and then, I would have made the matrix class.
    Maybe this is the purpose of exercise - learn the memory manipulation routines + operators overloading
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    The exam is fundamentally broken:
    - Only Dtor needs to be implemented
    Firstly, if taken literally, you only need to implement that one function. But clearly you then cant meet your other requirements.
    The exam actively encourages you to break the rule of three, and as such you will end up with code that is broken.
    It also encourages absurdities like adding a matrix and a string, yet as far as I can see does not explain WTF that is supposed to do.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  8. #8
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Quote Originally Posted by iMalc View Post
    It also encourages absurdities like adding a matrix and a string.
    With the code shown in the first post, it doesn't make sense. You have a matrix of pointers to strings, and you want to add (append) another matrix, that's OK as long as both matrices have the same number of columns, but then it shows addition with a string literal. Assume a matrix of pointers mpa[4][3], the string literal could be considered to be a matrix of pointers mps[1][1], and the matrices are not compatable (append wise).

    Assuming the normal interpretation for a 2d matrix as an array of pointers, an example case: mat1 is char *mp1[5] (5 rows), and mat2 is char *mp2[4] (4 rows). The add operation creates a new matrix of char *mp3[9], 9 rows, where the first 5 rows are a copy of the strings (new(1+strlen()), strcpy()), from mat1 and the last 4 rows are a copy of the strings from mat2. If mat2 is a literal, then consider it as char *mps[1]. I'm not sure how the add operator would determine if an operand is a matrix or just a pointer to string except by having multiple versions based on parameters (mat + mat, mat + str, str + mat, str + str). The matrix structure would need a pointer (row) count.

  9. #9
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    555
    It's not a matrix, it's just a 2D char array. So why are they calling it a matrix? How do you add these things together if they're strings? What is the intended result? Concatenation? Comparison and replacement?

  10. #10
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    I think that the OP just gave us what he thought was a good enough explanation and it is likely we aren't getting the correct or whole picture.
    Anything 2-D is technically a matrix, but the operations are basically left unexplained, which in C++ is a fatal mistake. Operators don't have a consistent meaning because of overloading, so it is best to explain what binary plus (or whatever) is supposed to do instead of giving usage examples, which are nearly always uninformative.
    Last edited by whiteflags; 09-28-2013 at 07:11 PM.

  11. #11
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Quote Originally Posted by nonpuz View Post
    It's not a matrix, it's just a 2D char array.
    In the code shown by the original poster, it's a 3D char array. I don't think that was the intention of the exercise.

  12. #12
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    How do you decide if add for string should append strings or instead produce a string that is the sum of the characters in the first string added to the second string? In the high level language APL, which handles generic types, scalars, vectors, matrices, tensors (3d or greater), + always means to add elements, and a different operator is used for append / concatenate.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Assigning int32_t to std::string, should this be allowed?
    By frogger in forum C++ Programming
    Replies: 5
    Last Post: 05-08-2011, 10:22 PM
  2. Public: ~Class() is allowed?
    By Lincoln_Poh in forum C++ Programming
    Replies: 13
    Last Post: 09-27-2008, 10:04 PM
  3. Replies: 8
    Last Post: 10-21-2007, 01:38 PM
  4. header file using a string in a class
    By linucksrox in forum C++ Programming
    Replies: 1
    Last Post: 04-21-2005, 03:06 PM
  5. Please help with String class, returning strings
    By skanxalot in forum C++ Programming
    Replies: 4
    Last Post: 09-24-2003, 10:48 AM