Nabeel Ahmed Mufti
Nabeel Ahmed Mufti

Reputation: 67

What is the problem of this code in c++? I've to work with c-string

I have created an array of c-string. this code takes input for three strings and then displays it on the console. but unfortunately, the input is fine but the output display doesn't working.

int main()
{
    char *str[20];
    std::cout << "Enter values to strings: ";
    for (int i = 0; i < 3; i++)
    {
        std::cout << "\nstr" << i<<": ";
        std::cin >> str[i];
    }
    std::cout << "\n\n\nouput:";
    for (int i = 0; i < 3; i++)
    {
        std::cout << "\nstr" << i<<":";
        std::cout << str[i];
    }
    return 0;
}
    

Upvotes: 1

Views: 101

Answers (1)

pptaszni
pptaszni

Reputation: 8218

As mentioned in the comments, using uninitialized pointers is undefined behavior. If you need to work with C-strings (i.e. you cannot use std::string, which I would normally recommend), just allocate the memory for your C-string with operator new. One possible approach is to define some constant max length of the expected input string, read input to the buffer, then allocate necessary memory and copy the data to the newly allocated space:

#include <iostream>
#include <cstring>

constexpr int MAX_STR_LEN = 255;

int main()
{
    char *str[20];
    char buff[MAX_STR_LEN];  // going to read strings here and copy them to `str` array
    std::memset(buff, 0, MAX_STR_LEN);  // fill the buffer with zeroes
    std::cout << "Enter values to strings: ";
    for (int i = 0; i < 3; i++)
    {
        std::cout << "\nstr" << i<<": ";
        std::cin >> buff;
        str[i] = new char[std::strlen(buff)+1];  // +1 for terminating null
        std::memcpy(str[i], buff, std::strlen(buff));
        str[i][std::strlen(buff)] = 0;  // last character should be null
    }
    std::cout << "\n\n\nouput:";
    for (int i = 0; i < 3; i++)
    {
        std::cout << "\nstr" << i<<":";
        std::cout << str[i];
        delete[] str[i];
    }
    return 0;
}

Note that this example is good for exercise purpose only, normally C++ developer would use std::vector<std::string> to keep dynamic array of strings.

Upvotes: 3

Related Questions