简体   繁体   English

我的程序在 char* 数组的第 3 个初始化周期中断。 不明白为什么会这样。 请解释

[英]My program breaks at 3rd cycle of initialization of array of char*. Cannot understand why it happens. Explain, please

If I try to run program and ititialize only 2 strings (char*), it works OK.如果我尝试运行程序并仅初始化 2 个字符串 (char*),它可以正常工作。 But when I try 3, 4 and more strings initialize, then program just stops.但是当我尝试初始化 3 个、4 个和更多字符串时,程序就会停止。 What do I miss?我想念什么?

#include <iostream>
#include <cstring>

template <typename T>
T maxn(T*, int);
template <> char* maxn(char**, int);
template <typename T>
void fill_array(T*, int);

int main()
{
    using std::cout;
    using std::cin;
    int N;
    cout << "Input size of array of integers: ";
    cin >> N;
    int *Arr = new int[N];
    fill_array(Arr, N);
    cout << "\nMax number in your array is " << maxn(Arr, N) << '\n';
    delete [] Arr;
    cout << "Input size of array of doubles: ";
    cin >> N;
    double *ArrDouble = new double[N];
    fill_array(ArrDouble, N);
    cout << "\nMax number in your array is " << maxn(ArrDouble, N) << '\n';
    delete [] ArrDouble;
    cout << "Input number of strings, that you plan to input: ";
    cin >> N;
    cin.get();
    char **ArrChar = new char*[N];
    for (int i=0; i<N; i++)
    {
        cout << "Input string #" << i+1 << ": ";
        cin.getline(ArrChar[i], 40);
    }
    cout << "The longest string starts at " << reinterpret_cast<void*>(maxn(ArrChar, N)) << " address";
    delete [] ArrChar;
    return 0;
}

template <typename T>
void fill_array(T* p_T, int N)
{
    for (int i=0; i<N; i++)
    {
        std::cout << "Enter a number #" << i+1 << ": ";
        std::cin >> p_T[i];
    }
    std::cout << "Array was initializated. Well done!\n";
    return;
}

template <typename T>
T maxn(T* p_T, int N)
{
    T max=p_T[0];
    for (int i=0; i<N-1; i++)
    {
        if (p_T[i]<p_T[i+1]) max=p_T[i+1]; 
    }
    return max;
}

template <> char* maxn(char** str, int N)
{
    char* max_len=&str[0][0];
    for (int i=0; i<N-1; i++)
    {
        if (strlen(str[i])<strlen(str[i+1])) max_len=&str[i+1][0];
    }
    return max_len;
}

I suppose, that problem chains with allocate memory, but don't sure.我想,这个问题与分配 memory 相关联,但不确定。 I tried it with fixwd-size array - program breaks after input first string...我尝试使用 fixwd-size 数组 - 输入第一个字符串后程序中断......

Change this改变这个

char **ArrChar = new char*[N];
for (int i=0; i<N; i++)
{
    cout << "Input string #" << i+1 << ": ";
    cin.getline(ArrChar[i], 40);
}

to this对此

char **ArrChar = new char*[N];
for (int i=0; i<N; i++)
{
    ArrChar[i] = new char[40]; // <-- ADD THIS!
    cout << "Input string #" << i+1 << ": ";
    cin.getline(ArrChar[i], 40);
}

You need to allocate some memory for your strings, getline won't do that for you.您需要为您的字符串分配一些 memory, getline不会为您这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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