Ошибка c2109 для индекса требуется массив или указатель

HakimotoX

0 / 0 / 0

Регистрация: 10.11.2010

Сообщений: 22

1

10.11.2010, 08:26. Показов 9764. Ответов 4

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Доброго времени суток!

Будьте так добры помочь в данном вопросе, как сделать указатель для этой части кода:

C++
1
2
3
4
if(a[i]>0)
{
    sum = sum + a[i];
}

Код всей программы:

Показать:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include "stdafx.h"
 
#include <stdio.h>
#include <math.h>
#include <clocale>
#include <memory.h>
#include <stdlib.h>
#include <time.h>
 
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
 
int _tmain(int argc, _TCHAR* argv[])
{
    _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
 
    setlocale(LC_ALL, "Russian");
    setlocale(LC_ALL, "rus");
 
    int menu = 0;
    int size = 0;
    double res, a, sum = 0;
 
    int wasEnt = 0;
    int wasCalc = 0;
    
    do
    {
        printf("\n");
        printf("+-----------------------------------------------------------------------------+\n");
        printf("|†† Программа для работы с массивом ††                                        |\n");
        printf("|                                                                             |\n");
        printf("|1. Ввести размер массива                                                     |\n");
        printf("|2. Вывести на экран исходный массив                                          |\n");
        printf("|3. Расчитать среднее арифметическое всех положительных элементов массива     |\n");
        printf("|4. Расчитать сумму элементов, расположенных до максимального элемента массива|\n");
        printf("|5. Вывести результат вычеслений                                              |\n");
        printf("+-----------------------------------------------------------------------------+\n");
        printf(" 0. Выход\n\n");
        printf("Выберете пункт меню: ");
 
        scanf("%d", &menu);
 
        srand(time(NULL));
 
        switch(menu)
        {
        case 1:
            {
                printf("\nВведите размер массива: ");
                scanf("%d", &size);
                printf("ввод завершен...");
                printf("\n\n");
                system("pause");
            }
            wasEnt = 1;
            wasCalc = 0;
            break;
        case 2:
            if (1 == wasEnt)
            {
                int *a = new int [size];
                memset(a, 0, size * sizeof(int));
 
                for (int i = 0; i < size; ++i)
                {
                    a[i] = rand() % 10;
                }
                printf("\nИсходный массив: \n\n");
                for (int i = 0; i < size; ++i)
                {
                    printf("[%d] ", a[i]);
                    wasCalc = 1;
                }
                printf("\n\n");
                system("pause");
            }
            else
            {
                printf("\n\aОШИБКА! Сначала введите размер массива! Выберете пункт меню 1.\n");
                printf("\n");
                system("pause");
            }
            break;
        case 3:
            if (wasCalc)
            {
                for (int i = 0; i < size; ++i)              
                {
                    if(a[i]>0)
                    {
                        sum = sum + a[i];
                    }
                    res = sum / size;
                    wasCalc = 1;
                }
                printf("Расчет закончен успешно! sum = %.2f\n", res);  
            }
            else
            {
                printf("\n\aОШИБКА! Сначала проверьте исходный массив! Выберете пункт меню 2.\n");
                printf("\n");
                system("pause");
            }
            break;
        case 0:
            break;
        default:
            printf("\n\aОШИБКА! Неверный пункт меню!\n");
            printf("\n");
            system("pause");
        }
 
 
    
    } while (menu != 0);
 
    return 0;
}

Если case 3: совместить с case 2: то все работает, но тогда теряется смысл операторов switch / case…

Ошибка 4 error C2109: для индекса требуется массив или указатель < — > строка [92]
Ошибка 5 error C2109: для индекса требуется массив или указатель < — > строка [94]

Заранее спасибо за помощь!



0



accept

4866 / 3288 / 468

Регистрация: 10.12.2008

Сообщений: 10,570

10.11.2010, 08:40

2

C++
1
int *a = new int [size];

переделать в

C++
1
a = new int [size];

при этом вот отсюда

C++
1
2
3
    int menu = 0;
    int size = 0;
    double res, a, sum = 0;

удалить a и записать его тут же

C++
1
2
3
    int menu = 0, size = 0;
    int *a;
    double res, sum = 0.0;

выделенную память нужно освобождать
нужно ещё поставить запрет на повторное выделение памяти (флажок, который переключить при первом выделении)



1



HakimotoX

0 / 0 / 0

Регистрация: 10.11.2010

Сообщений: 22

11.11.2010, 16:51

 [ТС]

3

Цитата
Сообщение от accept
Посмотреть сообщение

выделенную память нужно освобождать
нужно ещё поставить запрет на повторное выделение памяти (флажок, который переключить при первом выделении)

То, что нужно освобождать я знаю, оператор delete [] a; стоит в case 3:
А как сделать запрет, можно поподробней?

Вот готовая программа:

Показать:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include "stdafx.h"
 
#include <stdio.h>
#include <math.h>
#include <clocale>
#include <memory.h>
#include <stdlib.h>
#include <time.h>
 
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
 
int _tmain(int argc, _TCHAR* argv[])
{
    _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
 
    setlocale(LC_ALL, "Russian");
    setlocale(LC_ALL, "rus");
 
    int menu = 0, size = 0;
    int *a;
        double sArf = 0, sum = 0;
 
    int wasEnt = 0;
    int wasCalc = 0;
    
    do
    {
        printf("\n");
        printf("+-----------------------------------------------------------------------------+\n");
        printf("|†† Программа для работы с массивом ††                                        |\n");
        printf("|                                                                             |\n");
        printf("|1. Ввести размер массива                                                     |\n");
        printf("|2. Вывести на экран исходный массив                                          |\n");
        printf("|3. Расчитать среднее арифметическое всех положительных элементов массива     |\n");         
        printf("+-----------------------------------------------------------------------------+\n");
        printf(" 0. Выход\n\n");
        printf("Выберете пункт меню: ");
 
        scanf("%d", &menu);
 
        srand(time(NULL));
 
        switch(menu)
        {
        case 1:
            do
            {
                printf("\nВведите размер массива: ");
                scanf("%d", &size);
                if (size <= 0)
                {
                    printf("\n\aОШИБКА!: Число должно быть больше нуля!\nвведите еще раз...\n");
                }
                else
                {
                printf("ввод завершен...");
                printf("\n\n");
                system("pause");
                }
            } while (size <= 0);
            sum = 0;
            wasEnt = 1;
            wasCalc = 0;
            break;
        case 2:
            if (1 == wasEnt)
            {                       
                a = new int [size];
                memset(a, 0, size * sizeof(int));
 
                for (int i = 0; i < size; ++i)
                {
                    a[i] = rand() % 10;
                }
                printf("\nИсходный массив: \n\n");
                for (int i = 0; i < size; ++i)
                {
                    printf("[%d] ", a[i]);
                    sum = 0;
                    wasCalc = 1;
                }
                printf("\n\n");
                system("pause");                
            }
            else
            {
                printf("\n\aОШИБКА!: Сначала введите размер массива! Выберете пункт меню 1.\n");
                printf("\n");
                system("pause");
            }
            break;
        case 3:
            if (wasCalc)
            {               
                for (int i = 0; i < size; ++i)              
                {
                    sum = sum + a[i];                   
                    sArf = sum / size;
                }
                printf("\nРасчет закончен успешно!\n");
                printf("\nСреднее арифметическое равно: %.2f\n\n", sArf);
                system("pause");
                wasCalc = 0;
                delete [] a;
            }
            else
            {
                printf("\n\aОШИБКА!: Сначала проверьте исходный массив! Выберете пункт меню 2.\n");
                printf("\n");
                system("pause");
            }
            break;
        case 0:
            break;
        default:
            printf("\n\aОШИБКА!: Неверный пункт меню!\n");
            printf("\n");
            system("pause");
        }       
    } while (menu != 0);
    
    return 0;
}

Я предполагаю 2 варианта, если при выборе меню в таком порядке:

1. Вариант:

— Выполняем операции в case 1:
— Выполняем операции в case 2:
//при повторном нажатии case 2: память первых элементов массива должна очищаться,
//а вторые учитываться.. соответственно и при тройном нажатии должно происходить тоже самое..
— Выполняем операции в case 3:

2. Вариант:

— Выполняем операции в case 1:
— Выполняем операции в case 2:
//при повторном нажатии case 2: вылетало сообщение, что необходимо выполнить
//case 1:
— Выполняем операции в case 3:

Буду признателен за помощь, в этой проблеме!



0



accept

4866 / 3288 / 468

Регистрация: 10.12.2008

Сообщений: 10,570

11.11.2010, 21:41

4

Цитата
Сообщение от HakimotoX

То, что нужно освобождать я знаю, оператор delete [] a; стоит в case 3:…

что-то не заметно в первой версии

да и освобождать нужно после цикла

Цитата
Сообщение от HakimotoX

А как сделать запрет, можно поподробней?

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
        case 2:
            if (1 == wasEnt) {                                               
                a = new int [size];
                memset(a, 0, size * sizeof(int));
 
                for (int i = 0; i < size; ++i) {
                    a[i] = rand() % 10;
                }
                printf("\nИсходный массив: \n\n");
 
                for (int i = 0; i < size; ++i) {
                    printf("[%d] ", a[i]);
                    sum = 0; /* эти две должны быть вне цикла */
                    wasCalc = 1; /* эти две должны быть вне цикла */
                }
                printf("\n\n");
                system("pause");                                
            } else {
                printf("\n\aОШИБКА!: Сначала введите размер массива! Выберете пункт меню 1.\n");
                printf("\n");
                system("pause");
            }
            break;

добавляем кое-что

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    int menu = 0, size = 0;
    double sArf = 0, sum = 0;
    int *a, allocflag;
 
    int wasEnt = 0;
    int wasCalc = 0;
 
    allocflag = 0;
 
...
 
        case 2:
            if (1 == wasEnt) {                                               
                if (allocflag == 0) {
                    allocflag = 1;
                    a = new int [size];
                }
 
                memset(a, 0, size * sizeof(int));
 
                for (int i = 0; i < size; ++i) {
                    a[i] = rand() % 10;
                }
                printf("\nИсходный массив: \n\n");
 
                for (int i = 0; i < size; ++i) {
                    printf("[%d] ", a[i]);
                    sum = 0; /* эти две должны быть вне цикла */
                    wasCalc = 1; /* эти две должны быть вне цикла */
                }
                printf("\n\n");
                system("pause");                                
            } else {
                printf("\n\aОШИБКА!: Сначала введите размер массива! Выберете пункт меню 1.\n");
                printf("\n");
                system("pause");
            }
            break;

Добавлено через 2 минуты

Цитата
Сообщение от HakimotoX

Я предполагаю 2 варианта, если при выборе меню в таком порядке:

надо предполагать любой выбор в любой момент

Добавлено через 1 минуту

Цитата
Сообщение от HakimotoX

То, что нужно освобождать я знаю, оператор delete [] a; стоит в case 3:…

а если не будет входа в case 3 ?



1



0 / 0 / 0

Регистрация: 10.11.2010

Сообщений: 22

12.11.2010, 09:54

 [ТС]

5

Цитата
Сообщение от accept
Посмотреть сообщение

что-то не заметно в первой версии

В первой версии, меня другой вопрос интересовал..

Цитата
Сообщение от accept
Посмотреть сообщение

а если не будет входа в case 3 ?

А точно, тогда в конце нужно поставить.. благодарствую за помощь еще раз!



0



I am trying to debug some homework but I am having trouble with these lines of code

#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;

int main()
{
   char word;
   cout << "Enter a word and I will tell you whether it is" << endl <<
 "in the first or last half of the alphabet." << endl << 
   "Please begin the word with a lowercase letter. --> ";
   cin >> word;
   if(word[0] >= 'm')
     cout << word << " is in the first half of the alphabet" << endl;
   else
     cout << word << " is in the last half of the alphabet" << endl;
   return 0;
}  

I get the following error and I have no clue what its sayings

error C2109: subscript requires array or pointer type

Deanie's user avatar

Deanie

2,3152 gold badges19 silver badges35 bronze badges

asked May 13, 2010 at 20:13

numerical25's user avatar

numerical25numerical25

10.5k36 gold badges130 silver badges209 bronze badges

The term subscript refers to the application of [] operator. In your word[0], the [0] part is a subscript.

The built-in [] operator can only be used with arrays or pointers. You are trying to use it with an object of type char (your word is declared as char), which is neither an array nor a pointer. This is what the compiler is telling you.

answered May 13, 2010 at 20:15

AnT stands with Russia's user avatar

2

Another suggestion: declare output text as one entity, then block write. This may make your programs easier to debug, read and understand.

int main(void)
{
    static const char prompt[] =
    "Enter a word and I will tell you whether it is\n"
    "in the first or last half of the alphabet.\n"
    "Please begin the word with a lowercase letter. --> ";

   string word;
   cout.write(prompt, sizeof(prompt) - sizeof('\0'));

   getline(cin, word);

   cout << word;
   cout << "is in the ";
   if(word[0] >= 'm')
     cout "first";
   else
     cout << "last";

   cout << " half of the alphabet\n";
   return 0;
}

For Your Information (FYI):

  1. stdafx.h is not a standard header
    and not required for small projects.
  2. conio.h is not a standard header
    and not required for simple console
    I/O.
  3. Prefer string for text rather than
    char *.

answered May 13, 2010 at 21:54

Thomas Matthews's user avatar

Thomas MatthewsThomas Matthews

56.9k17 gold badges99 silver badges154 bronze badges

Instead of

char word;

declare

string word;

You already included the string-class header. Then you can access the elements with the []-operator.

Additional remark: Why do you use conio.h? It is obsolete and is not part of the C++ standard.

answered May 13, 2010 at 20:36

Lucas's user avatar

2

word is declared as a char, not an array. But you’re using word[0].

answered May 13, 2010 at 20:14

dcp's user avatar

dcpdcp

54.5k23 gold badges144 silver badges164 bronze badges

#include <stdio.h>
#include <iostream>

using namespace std;

    int main(void)
    {
bool premiereLignefaite = false;
//Lire le fichier
FILE * graphe = fopen("graphe.txt", "r");
//Fichier de sortie
FILE * resultat = fopen("resultat.txt", "w");
int nbr1, nbr2;
int *matrice; //pointeur vers la matrice d'adjacence

//Ligne lue
static char ligne[50];

while (fgets(ligne, 50, graphe) != NULL) //retourne 0 quand on a end-of-file
{
    //La premiere ligne est différente
    if (premiereLignefaite == false) {
        //Initialiser une matrice d'adjacence NxN
        sscanf(ligne, "%d %d", &nbr1, &nbr2);
        matrice =  new int(nbr1 * nbr1); //Memoire dynamique pour la matrice dadjacence n x n
        premiereLignefaite = true;
        continue;
    }
    //On construit notre matrice d'adjacence
    sscanf(ligne, "%d %d", &nbr1, &nbr2);
    matrice[nbr1][nbr2] = 1;
}

int u = 2+2;


return 0;
 }

So I’m getting an error on this line :
matrice[nbr1][nbr2] = 1;
I’m just trying to build an adjacency list from a text file. I don’t understand what I’m doing wrong. Thank you.

EDIT: Since people ask about it, this is my graph file. The first line is the number of vertices and the number of edges(not useful imo)
The following lines are my edges, I use the first line to allocate memory for a NxN graph and the following lines to fill in my adjacency matrix.

9 20
0 1
0 2
1 0
1 2
1 3
1 5
2 0
2 1
2 3
3 1
3 2
3 4
4 3
5 1
5 6
5 7
6 5
6 8
7 5
8 6

Айгулька

0 / 0 / 0

Регистрация: 11.01.2011

Сообщений: 7

1

11.01.2011, 18:17. Показов 14431. Ответов 7

Метки нет (Все метки)


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <conio.h>
#include <stdlib.h>
 
 
int prost(int b)
{
int i,a;
    for(i=2;i<b;i++)
    {
    a=b%i;
    if(a==0) printf("Число НЕпростое n",b);
    else printf("Число простое n",b);
    }
    return 0;
};
int massiv(int t[100])
{
    int n,i;
    printf("Введите колличество элементов массива: n",n);
for(int i=0;i<n;i++)
{
    t[i]=rand()%201-200;
}
printf("массив: n",t[i]);
};
int _tmain(int argc, _TCHAR* argv[])
{
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
 
    int i,a=0;
printf("Введите число: n",a);
massiv(a[i]);
prost(a);
 
 
    return 0;
}

битый час пытаюсь исправить и не получается всё равно(
помогите плиз….>.<

Добавлено через 26 минут
up!!!!!!!!!

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Эксперт С++

5053 / 3114 / 271

Регистрация: 11.11.2009

Сообщений: 7,045

11.01.2011, 18:33

2

1

55 / 55 / 9

Регистрация: 18.03.2010

Сообщений: 345

Записей в блоге: 1

11.01.2011, 18:33

3

Цитата
Сообщение от Айгулька
Посмотреть сообщение

int i,a=0; //здесь ‘а’ — имя переменной
printf(«Введите число: n»,a);
massiv(a[i]);

// а сдесь а — это уже имя массива, хоть ‘а’ объявлена выше как переменная, а не как массив

2

Эксперт С++

5053 / 3114 / 271

Регистрация: 11.11.2009

Сообщений: 7,045

11.01.2011, 18:36

4

А, не, фиг, а надо объявить как массив

Добавлено через 1 минуту

0

romedal

55 / 55 / 9

Регистрация: 18.03.2010

Сообщений: 345

Записей в блоге: 1

11.01.2011, 18:47

5

C++
1
2
3
4
5
6
7
8
9
10
int massiv(int t[100]) // Здесь указано, что функция должна возвращать целое значение
{                            // но функция в конце так ничего и не возвращает, возможно надо объявить её как 
        int n,i;              //void massiv(int t[100]) 
        printf("Введите колличество элементов массива: n",n);
for(int i=0;i<n;i++)
{
        t[i]=rand()%201-200;
}
printf("массив: n",t[i]);
}; //здесь точка с запятой не нужны

1

0 / 0 / 0

Регистрация: 11.01.2011

Сообщений: 7

11.01.2011, 19:27

 [ТС]

6

сделала всё как написали и теперь другая ошибка: error C2664: massiv: невозможно преобразовать параметр 1 из ‘int’ в ‘int []’
блин целый день с этим заданием сижу(( пфффф

Добавлено через 1 минуту
up!!!!!!!

Добавлено через 2 минуты
блин может это поможет…задание изначально было такое: с использованием функций удалить из одномерного массива все простые числа….я отчаилась(

0

sandye51

программист С++

841 / 600 / 147

Регистрация: 19.12.2010

Сообщений: 2,014

11.01.2011, 19:47

7

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <locale.h>
 
int prost(int b)
{
    int i;
    for(i=2; i <= int(sqrt(double(b))); i++)
        if(!(b % i))
        {
            printf("nЧисло НЕпростое %dn", b);
            return 0;
        }
    printf("nЧисло простое %dn",b);
    return 1;
};
void massiv(int* t)
{
    int n, i;
    srand((unsigned)time(NULL));
    printf("Введите колличество элементов массива: n");
    scanf("%d", &n);
    t = new int[n];
    printf("массив: n");
    for(i=0;i<n;i++)
    {
        t[i]=rand()%201-200;
        printf("%d  ",t[i]);
    }
};
int main()
{
    setlocale(LC_ALL, "Russian");
 
    int *i = NULL,a;
    printf("Введите число: n");
    scanf("%d", &a);
    massiv(i);
    prost(a);
    getch();
    delete[]i;
    return 0;
}

1

0 / 0 / 0

Регистрация: 11.01.2011

Сообщений: 7

11.01.2011, 21:10

 [ТС]

8

спасииибо)
немножко подправила и рабоооотает)

0

I am trying to debug some homework but I am having trouble with these lines of code

#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;

int main()
{
   char word;
   cout << "Enter a word and I will tell you whether it is" << endl <<
 "in the first or last half of the alphabet." << endl << 
   "Please begin the word with a lowercase letter. --> ";
   cin >> word;
   if(word[0] >= 'm')
     cout << word << " is in the first half of the alphabet" << endl;
   else
     cout << word << " is in the last half of the alphabet" << endl;
   return 0;
}  

I get the following error and I have no clue what its sayings

error C2109: subscript requires array or pointer type

Deanie's user avatar

Deanie

2,3042 gold badges18 silver badges35 bronze badges

asked May 13, 2010 at 20:13

numerical25's user avatar

numerical25numerical25

10.4k35 gold badges128 silver badges208 bronze badges

The term subscript refers to the application of [] operator. In your word[0], the [0] part is a subscript.

The built-in [] operator can only be used with arrays or pointers. You are trying to use it with an object of type char (your word is declared as char), which is neither an array nor a pointer. This is what the compiler is telling you.

answered May 13, 2010 at 20:15

AnT stands with Russia's user avatar

2

Another suggestion: declare output text as one entity, then block write. This may make your programs easier to debug, read and understand.

int main(void)
{
    static const char prompt[] =
    "Enter a word and I will tell you whether it isn"
    "in the first or last half of the alphabet.n"
    "Please begin the word with a lowercase letter. --> ";

   string word;
   cout.write(prompt, sizeof(prompt) - sizeof(''));

   getline(cin, word);

   cout << word;
   cout << "is in the ";
   if(word[0] >= 'm')
     cout "first";
   else
     cout << "last";

   cout << " half of the alphabetn";
   return 0;
}

For Your Information (FYI):

  1. stdafx.h is not a standard header
    and not required for small projects.
  2. conio.h is not a standard header
    and not required for simple console
    I/O.
  3. Prefer string for text rather than
    char *.

answered May 13, 2010 at 21:54

Thomas Matthews's user avatar

Thomas MatthewsThomas Matthews

56.2k17 gold badges98 silver badges151 bronze badges

Instead of

char word;

declare

string word;

You already included the string-class header. Then you can access the elements with the []-operator.

Additional remark: Why do you use conio.h? It is obsolete and is not part of the C++ standard.

answered May 13, 2010 at 20:36

Lucas's user avatar

2

word is declared as a char, not an array. But you’re using word[0].

answered May 13, 2010 at 20:14

dcp's user avatar

dcpdcp

54k22 gold badges141 silver badges164 bronze badges

Permalink

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Go to file

  • Go to file

  • Copy path


  • Copy permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2109

Compiler Error C2109

11/04/2016

C2109

C2109

2d1ac79d-a985-4904-a38b-b270578d664d

Compiler Error C2109

subscript requires array or pointer type

The subscript was used on a variable that was not an array.

The following sample generates C2109:

// C2109.cpp
int main() {
   int a, b[10] = {0};
   a[0] = 1;   // C2109
   b[0] = 1;   // OK
}

Permalink

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Go to file

  • Go to file

  • Copy path


  • Copy permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2109

Compiler Error C2109

11/04/2016

C2109

C2109

2d1ac79d-a985-4904-a38b-b270578d664d

Compiler Error C2109

subscript requires array or pointer type

The subscript was used on a variable that was not an array.

The following sample generates C2109:

// C2109.cpp
int main() {
   int a, b[10] = {0};
   a[0] = 1;   // C2109
   b[0] = 1;   // OK
}

Я столкнулся с небольшой проблемой, связанной с циклом for и массивом, и я надеюсь, что смогу получить некоторую помощь. В первой функции использование цикла for для вызова каждого значения функции работает просто отлично. Тем не менее, во второй функции я получаю сообщение об ошибке из Visual Studio о том, что «индекс требует массив или тип указателя». Что я делаю не так здесь, что вызывает эту ошибку?

Целью этой программы является поиск в текстовом файле книг, пропуск строк между записями, выяснение, сколько записей в файле соответствует и где они находятся, и распечатка деталей каждой записи.

void bookSearch(string id) {
ifstream fbooks;

string item = " ", entry = " ";

int resultLocation[30];

int searchType = 0;

fbooks.open("books.txt");

cout << "Welcome to the Book Search System, " << id << ".n"<< "What do you wish to search the registry by?n"<< "1. ISBN Numbern" << "2. Authorn" << "3. Titlen";

while (searchType<1 || searchType>3) {
cin >> searchType;

if (searchType<1 || searchType>3) {
displayMessage(0);

}
}

getline(cin, item);

for (int x = 0; x <= 30; x++) {
for (int y = 0; y < searchType; y++)
getline(fbooks, entry);

if (entry == item)
resultLocation[x] = 1;
else
resultLocation[x] = 0;

for (int z = 0; z < 5; z++)
getline(fbooks, entry);
}

resultPrint(resultLocation, id);
}void resultPrint(int resultLocation, string id){
int resultNum = 0;

string entry = "";

ifstream fbooks;

fbooks.open("books.txt");

for (int a = 0; a <= 30; a++) {
if (resultLocation == 1)
resultNum++;
}

if (resultNum > 0) {
cout << endl << "There are " << resultNum << " entries in the database matching that criteria.n";

for (int a = 0; a <= 30; a++){
if (resultLocation[a] == 1) { //The a in this line is marked with the error
for (int b = 0; b <= 2; b++) {
getline(fbooks, entry);
cout << entry;
}
}
}
}

else
cout << endl << "There are no entries in the database matching that criteria.n";
}

0

Решение

resultLocation является целым числом, поэтому вы не можете использовать operator[] на нем (кроме первого «указателя»). Похоже, вы хотели создать массив:

void resultPrint(int resultLocation[], string id);

0

Другие решения

  • Forum
  • Beginners
  • error C2109: subscript requires array or

error C2109: subscript requires array or pointer type

Hi everyone, I’m new to C++ programming. I got a task to sort students mark in ascending order using bubble sorting. The marks are given in the text file. I had try to solve it but error still occurred and i don’t know how to solve the errors. Hoping anyone can help me. Thanks for your kindness.

Here is the text file. (first column indicate matricNum, second column marks and third are gender)
001 65.5 2
002 56.7 2
003 35.8 1
004 42 2
005 49.4 1
006 55.1 1
007 87.5 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;

int main()

{
	double numb[7];
	int i, j;
	double temp;
	int matricNum;
	double marks;
	int gender;

	// store data into array.
    {
        // open the file for input
        ifstream inputFile("myFile.txt");

        // the input file was opened 
        for( int i = 0; i < 7; i++ )
        inputFile >> matricNum[i] >> marks[i] >> gender[i];

        // the file is closed
    }

	//sort marks in ascending order using bubble sort

	for (i=0;i<=7;i++)
	{
		for (j=i+1;j<=6;j++)
		{

			if (marks[i] > marks[j])
			{
				temp = marks[i];
				marks[i] = marks[j];
				marks[j] = temp;
			}
		}
	}

	for (i=0;i<=6;i++)
	{
		cout << matricNum << marks[i] << gender << endl;
	}

	system("pause");
}

The output should be:
003 35.8 1
004 42 2
005 49.4 1
006 55.1 1
002 56.7 2
001 65.5 2
007 87.5 2

error C2109: subscript requires array or pointer type

Does your compiler/IDE show the line that causes that error? It should.

Lines 24, 36, 38, 39, 40, 47:

1
2
3
4
5
int matricNum; // one number
double marks; // one number
int gender; // one number

inputFile >> matricNum[i] >> marks[i] >> gender[i];

You do use those three variables like they were arrays.

Then again, you never use the array double numb[7];

Hi yat89,

Errors/warnings for your file:

 In function 'int main()':
24:33: error: invalid types 'int[int]' for array subscript
24:45: error: invalid types 'double[int]' for array subscript
24:58: error: invalid types 'int[int]' for array subscript
36:15: error: invalid types 'double[int]' for array subscript
36:26: error: invalid types 'double[int]' for array subscript
38:19: error: invalid types 'double[int]' for array subscript
39:12: error: invalid types 'double[int]' for array subscript
39:23: error: invalid types 'double[int]' for array subscript
40:12: error: invalid types 'double[int]' for array subscript
47:31: error: invalid types 'double[int]' for array subscript
10:9: warning: unused variable 'numb' [-Wunused-variable]

I believe your issue is that you never actually use your numb array.
Your error is that you are attempting to use matricNum as an array (by accessing it as matricNum[i]), but matricNum is simple an int.

Perhaps you meant to use numb instead of matricNum?

Similarly, marks

is not an array

.
If you want it to be an array, declare it as such,
perhaps double marks[7];

Last,
for (i=0;i<=7;i++)
Please note that if your array has 7 elements in it, accessing my_array[7] is out of bounds of the array, because arrays start at 0.
I would change the <= to just <.

Last edited on

Topic archived. No new replies allowed.

  • Remove From My Forums
  • Question

  • i am trying to create n sequences of vector  and each with different number of elements.

    So, first i create the number of sequences which is n, then i also create the index for each sequence. Last, i enter the elements for each sequence. 

    i have been thinking for like half an hour, and still have no clue where went wrong. can someone tell me where?

    int main()
    {
     int n,number;
     cin>>n;
      vector<int> array;
    array.resize(n);

      for (int x=0; x<n; x++)
      {
          cin>>number;
          for (int y=0; y<number; y++)
          {
          cin>>array[x][y];
          }
      }

    }

Answers

  • array is a vector of int. 
    array[x] is an element of this vector.  Therefore it is an int.
    array[x][y] is a meaningless expression because you cannot apply the expression [y] to an int.

    You talk of a sequence of vectors. In order for that to happen, you need to have more than one vector. You have a couple of options:
         You could define a vector of vectors — vector<vector<int>> array;
         You could define an array of vectors — vector<int> array[10];

    While technically still only one vector, you could also define a vector of arrays — vector<int[100]> array; which would allow you to use the syntax array[x][y].

    On the other hand, if you tell us what you want to do rather than how you intend to do it, we may be able to offer better suggestions.

    • Proposed as answer by

      Monday, September 26, 2016 7:04 AM

    • Marked as answer by
      Hart Wang
      Monday, October 10, 2016 6:22 AM
#include <stdio.h>
#include <iostream>

using namespace std;

    int main(void)
    {
bool premiereLignefaite = false;
//Lire le fichier
FILE * graphe = fopen("graphe.txt", "r");
//Fichier de sortie
FILE * resultat = fopen("resultat.txt", "w");
int nbr1, nbr2;
int *matrice; //pointeur vers la matrice d'adjacence

//Ligne lue
static char ligne[50];

while (fgets(ligne, 50, graphe) != NULL) //retourne 0 quand on a end-of-file
{
    //La premiere ligne est différente
    if (premiereLignefaite == false) {
        //Initialiser une matrice d'adjacence NxN
        sscanf(ligne, "%d %d", &nbr1, &nbr2);
        matrice =  new int(nbr1 * nbr1); //Memoire dynamique pour la matrice dadjacence n x n
        premiereLignefaite = true;
        continue;
    }
    //On construit notre matrice d'adjacence
    sscanf(ligne, "%d %d", &nbr1, &nbr2);
    matrice[nbr1][nbr2] = 1;
}

int u = 2+2;


return 0;
 }

Итак, я получаю сообщение об ошибке в этой строке:
matrice [nbr1] [nbr2] = 1;
Я просто пытаюсь создать список смежности из текстового файла. Я не понимаю, что я делаю неправильно. Спасибо.

EDIT: поскольку люди спрашивают об этом, это мой графический файл. Первая строка — количество вершин и число ребер (не полезно imo)
Следующие строки являются моими ребрами, я использую первую строку для выделения памяти для графика NxN и следующих строк для заполнения моей матрицы смежности.

9 20
0 1
0 2
1 0
1 2
1 3
1 5
2 0
2 1
2 3
3 1
3 2
3 4
4 3
5 1
5 6
5 7
6 5
6 8
7 5
8 6
  • Remove From My Forums
  • Question

  • i am trying to create n sequences of vector  and each with different number of elements.

    So, first i create the number of sequences which is n, then i also create the index for each sequence. Last, i enter the elements for each sequence. 

    i have been thinking for like half an hour, and still have no clue where went wrong. can someone tell me where?

    int main()
    {
     int n,number;
     cin>>n;
      vector<int> array;
    array.resize(n);

      for (int x=0; x<n; x++)
      {
          cin>>number;
          for (int y=0; y<number; y++)
          {
          cin>>array[x][y];
          }
      }

    }

         

Answers

  • array is a vector of int. 
    array[x] is an element of this vector.  Therefore it is an int.
    array[x][y] is a meaningless expression because you cannot apply the expression [y] to an int.

    You talk of a sequence of vectors. In order for that to happen, you need to have more than one vector. You have a couple of options:
         You could define a vector of vectors — vector<vector<int>> array;
         You could define an array of vectors — vector<int> array[10];

    While technically still only one vector, you could also define a vector of arrays — vector<int[100]> array; which would allow you to use the syntax array[x][y].

    On the other hand, if you tell us what you want to do rather than how you intend to do it, we may be able to offer better suggestions.

    • Proposed as answer by

      Monday, September 26, 2016 7:04 AM

    • Marked as answer by
      Hart Wang
      Monday, October 10, 2016 6:22 AM

Понравилась статья? Поделить с друзьями:
  • Ошибка c2000 kyocera 2035
  • Ошибка c1731 крафтер
  • Ошибка c1831 lexus gx470
  • Ошибка c2109 джип гранд чероки
  • Ошибка c1726 тойота прадо 120