Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializer-string for array of chars is too long

Tags:

c++

arrays

char

I keep getting this error: initializer-string for array of chars is too long Even if I change num and length to 1, it still gets the error:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    const int num = 11;
    const int length = 25;
    char array[num][length] = { "Becky Warre, 555-1223"
                                "Joe Looney, 555-0097"
                                "Geri Palmer, 555-8787"
                                "Lynn Presnell, 555-1212"
                                "Holly Gaddis, 555-8878"
                                "Sam Wiggins, 555-0998"
                                "Bob Kain, 555-8712"
                                "Tim Haynes, 555-7676"
                                "Warren Gaddis, 555-9037"
                                "Jean James, 555-4939"
                                "Ron Palmer, 555-2893" };

    char search[length];
    cout << "Enter a string to search: ";
    cin.getline(search, length);

    char *ptr = NULL;
    int i;
    for (i = 0; i < num; i++)
    {
        ptr = strstr(array[num], search);
        if (ptr != NULL)
            cout << array[i];
    }
    if (ptr == NULL)
        cout << "No match found" << endl;

    return 0;
}
like image 472
Raptrex Avatar asked Dec 02 '22 07:12

Raptrex


2 Answers

I think it's because there aren't any commas in your array initialization...

char array[num][length] = { "Becky Warre, 555-1223",
                            "Joe Looney, 555-0097",
                            "Geri Palmer, 555-8787",
                            "Lynn Presnell, 555-1212",
                            "Holly Gaddis, 555-8878",
                            "Sam Wiggins, 555-0998",
                            "Bob Kain, 555-8712",
                            "Tim Haynes, 555-7676",
                            "Warren Gaddis, 555-9037",
                            "Jean James, 555-4939",
                            "Ron Palmer, 555-2893" }
like image 72
Quintin Robinson Avatar answered Dec 24 '22 11:12

Quintin Robinson


Seems you forgot to add comma's. Initializing a char* array is done like this:

char entries [number_of_items][lenght]  = { "entry1", "entry2", .... };

Apart from that, you can save yourself a lot of trouble by using an array of std::strings:

std::string entries[] = { "entry1", "entry2", ... };
like image 31
xtofl Avatar answered Dec 24 '22 09:12

xtofl