Search code examples
c++arraysstrcpy

'char' array issue, custom print function and strcpy_s problem


I just started C++ and now I'm making a simple program. But don't know how to fix this problem. I'm not a native english speaker so some sentences may not be understandable.

int main()
{
    char test[5][4] = { "abc", "def", "ghi", "jkl", "mno" };
    for (int i = 0; i < 5; ++i)
        std::cout << test[i] << "\t";
    
    return 0;
}

with this simple code, I made a print function

void printTest(char* pArr)
{
    for (int i = 0; i < 5; ++i)
        std::cout << pArr[i] << "\t";
}

Then in my main function, I typed printTest(*test); but the result was 'a b c d' while my expectation was 'abc def ghi jkl mno'


So I fixed printTest function like below (changed const char* test[5][4] = { ... } in main function)

void printTest(const char** pArr)
{
    for (int i = 0; i < 5; ++i)
        std::cout << pArr[i] << "\t";
}

which worked well.

The problem is, I want to use strcpy_s fucntion also. strcpy_s(test[0], "xyx"); like this.

As strcpy_s get char* for the first parameter (not const char*), I think I need to use char* for my array, and print function. While that thing cause a wrong printing issue.

Did i wrote something wrong in my printTest function? Or Is there any way that I can use strcpy_s function with const char* parameter?

PS. I used std::string and made it as I expected. But I want to have a understanding and control of Char array.


Solution

  • I don't think void printTest(const char** pArr) will work with char test[5][4].

    The c++ compiler should refuse something like

        void printTest(const char** pArr);
        char test[5][4];
        printTest(test);
    

    Because test is a pointer to char [4], while printTest() expects a pointer to char *.

    You may have interesting in this function:

        void printTest2(const char (*pArr)[4] )
        {
            for (int i = 0; i < 5; ++i)
                std::cout << pArr[i] << "\t";
            std::cout <<  "\n";
        }
    

    And the const keyword tells compiler (and what more important, the reader of your code) that "you won't modify the contents of 'pArr'". So compiler will not allow you to strcpy to pArr[i]. And this will compile and run.

    
    void printTest3(char (*pArr)[4] )
    {
        for (int i = 0; i < 5; ++i)
        {
            strcpy(pArr[i], "123");
            std::cout << pArr[i] << "\t";
        }
        std::cout <<  "\n";
    }
    ...
    printTest3(test);