This following code gets this compile error: «invalid types 'int[int]' for array subscript
«. What should be changed?
#include <iostream>
using namespace std;
int main(){
int myArray[10][10][10];
for (int i = 0; i <= 9; ++i){
for (int t = 0; t <=9; ++t){
for (int x = 0; x <= 9; ++x){
for (int y = 0; y <= 9; ++y){
myArray[i][t][x][y] = i+t+x+y; //This will give each element a value
}
}
}
}
for (int i = 0; i <= 9; ++i){
for (int t = 0; t <=9; ++t){
for (int x = 0; x <= 9; ++x){
for (int y = 0; y <= 9; ++y){
cout << myArray[i][t][x][y] << endl;
}
}
}
}
system("pause");
}
starball
15.2k6 gold badges29 silver badges136 bronze badges
asked Dec 12, 2008 at 19:25
You are subscripting a three-dimensional array myArray[10][10][10]
four times myArray[i][t][x][y]
. You will probably need to add another dimension to your array. Also consider a container like Boost.MultiArray, though that’s probably over your head at this point.
answered Dec 12, 2008 at 19:28
copprocoppro
14.3k5 gold badges58 silver badges73 bronze badges
1
What to change? Aside from the 3 or 4 dimensional array problem, you should get rid of the magic numbers (10 and 9).
const int DIM_SIZE = 10;
int myArray[DIM_SIZE][DIM_SIZE][DIM_SIZE];
for (int i = 0; i < DIM_SIZE; ++i){
for (int t = 0; t < DIM_SIZE; ++t){
for (int x = 0; x < DIM_SIZE; ++x){
answered Dec 12, 2008 at 20:00
jmucchiellojmucchiello
18.7k7 gold badges41 silver badges61 bronze badges
1
Just for completeness, this error can happen also in a different situation: when you declare an array in an outer scope, but declare another variable with the same name in an inner scope, shadowing the array. Then, when you try to index the array, you are actually accessing the variable in the inner scope, which might not even be an array, or it might be an array with fewer dimensions.
Example:
int a[10]; // a global scope
void f(int a) // a declared in local scope, overshadows a in global scope
{
printf("%d", a[0]); // you trying to access the array a, but actually addressing local argument a
}
Remy Lebeau
550k31 gold badges451 silver badges764 bronze badges
answered Jan 27, 2020 at 2:42
1
int myArray[10][10][10];
should be
int myArray[10][10][10][10];
thkala
83.6k23 gold badges156 silver badges199 bronze badges
answered Dec 12, 2008 at 19:30
CadooCadoo
7974 silver badges13 bronze badges
You’re trying to access a 3 dimensional array with 4 de-references
You only need 3 loops instead of 4, or int myArray[10][10][10][10];
thkala
83.6k23 gold badges156 silver badges199 bronze badges
answered Dec 12, 2008 at 19:28
DShookDShook
14.7k9 gold badges44 silver badges54 bronze badges
I think that you had intialized a 3d array but you are trying to access an array with 4 dimension.
answered Feb 4, 2018 at 17:25
1
I just forgot to put []
to the function parameter with array data type like this:
🚨 Instead of this:
void addToDB(int arr) {
// code
}
✅ Do this:
void addToDB(int arr[]) {
// code
}
answered Apr 27, 2022 at 17:47
Amir2miAmir2mi
7779 silver badges12 bronze badges
Trying to learn C++ and working through a simple exercise on arrays.
Basically, I’ve created a multidimensional array and I want to create a function that prints out the values.
The commented for-loop within Main() works fine, but when I try to turn that for-loop into a function, it doesn’t work and for the life of me, I cannot see why.
#include <iostream>
using namespace std;
void printArray(int theArray[], int numberOfRows, int numberOfColumns);
int main()
{
int sally[2][3] = {{2,3,4},{8,9,10}};
printArray(sally,2,3);
// for(int rows = 0; rows < 2; rows++){
// for(int columns = 0; columns < 3; columns++){
// cout << sally[rows][columns] << " ";
// }
// cout << endl;
// }
}
void printArray(int theArray[], int numberOfRows, int numberOfColumns){
for(int x = 0; x < numberOfRows; x++){
for(int y = 0; y < numberOfColumns; y++){
cout << theArray[x][y] << " ";
}
cout << endl;
}
}
Сообщение от mersinvald
А как правильно объявлять динамические массивы?
Как создать двумерный массив неконстантного размера в С++
Существует несколько способов. Рассмотрим их на примере двумерного массива ‘array’ размера N x M с элементами типа ‘int’. При этом ни N, ни M не являются константами времени компиляции.
1. Простейший способ: вектор векторов
C++ | ||
|
В результате будет определен вектор векторов, представляющий двумерный массив N x M, заполненный изначально нулями.
Синтаксис доступа — привычный ‘array[i][j]’.
Передача в функции — как ‘vector<vector<int>> &’
C++ | ||
|
В этом случае размеры массива в функцию передавать не надо, так как вектор уже хранит свой размер внутри себя.
2. Моделирование двумерного массива через одномерный с пересчетом индексов
C++ | ||
|
Это создаст одномерный массив размера N*M, заполненный нулями.
Чтобы доступиться к элементу по двумерному индексу [i][j] просто выполняем пересчет индексов по формуле ‘i * M + j’, т.е. доступаемся к элементу ‘array[i * M + j]’. (На самом деле именно так работают встроенный тип «массив» в языках С и С++ для любой размерности массива.)
Передача в функцию — очевидным образом
C++ | ||
|
Освобождение памяти
Понятно, что в этом способе вместо голого массива можно использовать ‘std::vector’.
3а. «Рваный» массив с индивидуальным выделением памяти
C++ | ||
|
Синтаксис доступа — привычный ‘array[i][j]’.
Передача в функции
C++ | ||
|
Освобождение памяти
C++ | ||
|
Несложно догадаться, что этот способ — это практически то же самое, что и способ 1, только с голыми массивами вместо векторов.
3б. «Рваный» массив с общим выделением памяти
C++ | ||
|
Синтаксис доступа и передача в функции — как и в предыдущем способе.
Освобождение памяти
C++ | ||
|
Если внимательно посмотреть на способ 2 и способ 3б, то можно заметить, что они очень похожи. В обоих случаях сами данные хранятся в одномерном массиве размера N*M. Разница только в том, что в способе 2 вычисление финального индекса делается через полную формулу, а в способе 3б это вычисление частично уже выполнено для начала каждой строки двумерного массива и указатели на эти начала сохранены в дополнительном массиве указателей.
Добавлено через 11 минут
Сообщение от mersinvald
А как правильно объявнять динамические массивы?
Разумеется, вышеприведенные разглагольствования на тему динамических массивов вам нужны только в том случае, если вам действительно нужен массив неконстантного размера в программе. Т.е. если величина ‘Size’, например, вводится пользователем или читается из файла, т.е. заранее не известна.
Если же величина ‘Size’ жестко задана на стадии компиляции, то все эти усилия становятся ненужными. Просто объявите ее глобально как
и смело пользуйтесь обычными встроенными массивами размера ‘Size’.
Are you facing an «invalid types int int for array subscript» error while working with arrays in your code? Don’t worry, you’re not alone. This error is a common problem faced by developers while working with arrays in C, C++, and other programming languages. In this guide, we’ll walk you through the steps to troubleshoot and fix this error.
Understanding the Error
Before we dive into the solution, let’s first understand what this error means. This error occurs when you try to use an index value that is not valid for an array. The index value can be an integer or any other data type. For example, if you have an array of size 5, and you try to access the 6th element of the array, you’ll get this error.
Troubleshooting Tips
Here are some troubleshooting tips to fix the «invalid types int int for array subscript» error:
1. Check the Array Size
The first thing you should check is the size of the array. Make sure that the index value you’re using is within the range of the array size. If the index value is greater than or equal to the size of the array, you’ll get this error.
2. Check the Index Value
Make sure that the index value you’re using is of the correct data type. For example, if you have an array of integers, the index value should also be an integer. If you use a different data type, you’ll get this error.
3. Check the Syntax
Check the syntax of your code. Make sure that you’re using the correct syntax to access the elements of the array. For example, if you’re using C++, you should use the square brackets to access the elements of the array.
4. Check for Typos
Check for typos in your code. Sometimes, a small typo can cause this error. Make sure that you’ve spelled the variable names and function names correctly.
5. Use a Debugger
If none of the above solutions work, try using a debugger. A debugger can help you pinpoint the exact location of the error in your code. Use the debugger to step through your code and find the line that is causing the error.
FAQ
Q1. What is the cause of the «invalid types int int for array subscript» error?
A1. This error occurs when you try to use an index value that is not valid for an array. The index value can be an integer or any other data type.
Q2. How do I fix the «invalid types int int for array subscript» error?
A2. You can fix this error by checking the size of the array, the index value, the syntax of your code, checking for typos, and using a debugger.
Q3. Can this error occur in any programming language?
A3. Yes, this error can occur in any programming language that supports arrays.
Q4. Is there any way to prevent this error from occurring?
A4. Yes, you can prevent this error from occurring by checking the size of the array and using the correct index value.
Q5. Can I use a try-catch block to handle this error?
A5. Yes, you can use a try-catch block to handle this error. However, it’s better to fix the error rather than handling it.
- Arrays in C Programming
- Arrays in C++ Programming
- Debugging Tools for C++ in Visual Studio
I am trying to get an Arduino to work with some Adafruit Motor shields.
Everything seemed to work fine, but when I tried to create a function, I get the error in the subject. As far as I can tell, everything was declared properly (the array is initialized and is indexed elsewhere with without issue). Only the function seems to cause an issue.
Would anyone have a guess at what’s wrong?
//////// Imports
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"
////////My globals. Times are in milliseconds
unsigned long currentTime = 0;
unsigned long elapsedTime = 0;
unsigned long startTime = 0;
byte currentMotor = 1;
byte currentShield = 1;
byte motorRunning = 0;
//// Settings
// How many seconds between motors
unsigned long endTime = 4000;
// How many shields and motors per shield
const int nShields = 1;
const int nMotorsPerShield = 3;
/////////MicroManager globals
unsigned int version_ = 2;
const unsigned long timeOut_ = 1000;
byte currentPattern_ = 0;
unsigned long time;
/////////Adafruit globals
Adafruit_MotorShield afms[nShields];
Adafruit_DCMotor *motor[nShields][nMotorsPerShield];
////////////Setup
void setup() {
Serial.begin(57600);
unsigned char address = 96;
for (int i = 0; i < nShields; i++) {
afms[i] = Adafruit_MotorShield(address);
address = ++address;
afms[i].begin();
}
for (int i = 0; i < nShields; i++) {
for (int j = 0; j < nMotorsPerShield; j++) {
motor[i][j] = afms[i].getMotor(j + 1);
motor[i][j]->setSpeed(255);
}
}
pinMode(13, OUTPUT);
}
////////////////////Main
void loop() {
currentTime = millis();
elapsedTime = currentTime - startTime;
if (elapsedTime > endTime) {
startTime = currentTime;
currentMotor = currentMotor + 1;
if (currentMotor > nMotorsPerShield) {
currentMotor = 1;
}
}
if (Serial.available() > 0) {
int inByte = Serial.read();
switch (inByte) {
case 1:
if (waitForSerial(timeOut_)) {
currentPattern_ = Serial.read();
if (currentPattern_ == 0) {
for (int i = 0; i < nShields; i++) {
for (int j = 0; j < nMotorsPerShield; j++) {
motor[1][j]->run(RELEASE);
}
}
}
else {
switchMotor();
}
Serial.write( byte(1));
digitalWrite(13, HIGH);
}
break;
case 30:
Serial.println("MM-Ard");
break;
case 31:
Serial.println(version_);
break;
}
}
digitalWrite(13, LOW);
}
////////////////Function definitions
bool waitForSerial(unsigned long timeOut)
{
unsigned long starTime = millis();
while (Serial.available() == 0 && (millis() - starTime < timeOut) ) {}
if (Serial.available() > 0)
return true;
return false;
}
void switchMotor()
{
int shield = currentShield - 1;
int motor = currentMotor - 1;
for (int i = 0; i < nShields; i++) {
for (int j = 0; j < nMotorsPerShield; j++) {
if (i == shield && j == motor)
motor[i][j]->run(FORWARD);
else
motor[i][j]->run(RELEASE);
}
}
}
Greenonline
2,8607 gold badges31 silver badges46 bronze badges
asked Feb 11, 2016 at 19:51
1
Take a close look at this line:
motor[1][j]->run(RELEASE);
Looks like it should be:
motor[i][j]->run(RELEASE);
Otherwise it is an illegal index (as there is only one shield).
The next error is in the function switchMotor(). Again, have a close look at the definition of «motor». There is a local variable with that name but you want to also access the global array with the same name.
void switchMotor()
{
int shield = currentShield - 1;
int motor = currentMotor - 1;
^
for (int i = 0; i < nShields; i++) {
for (int j = 0; j < nMotorsPerShield; j++) {
if (i == shield && j == motor)
motor[i][j]->run(FORWARD);
^
else
motor[i][j]->run(RELEASE);
}
}
}
My guess is that this is where the compiler give you the error message!
Cheers!
answered Feb 11, 2016 at 19:59
Mikael PatelMikael Patel
7,9292 gold badges12 silver badges21 bronze badges
3
I get a warning flag in UECIDE for the line:
address = ++address;
‣ operation on ‘address’ may be undefined [-Wsequence-point]
Increment address, and then assign the new value from address into address. That seems a bit odd to me. I think you just meant to increment:
address++;
Or
address = address + 1;
Also it flags up the 1
instead of i
that Mikael found:
‣ array subscript is above array bounds [-Warray-bounds]
And of course there is the (somewhat hard to spot — Kudos to Mikael for finding it — it took me a bit to see it myself) naming conflict:
‣ invalid types ‘int[int]’ for array subscript
It was only when I used the advanced editing facilities of UECIDE to highlight all occurrences of motor
that I found there was extra ones that shouldn’t have been there causing the problem.
So just changing the integer variable name from motor
to something else fixes it:
void switchMotor()
{
int shield = currentShield - 1;
int thismotor = currentMotor - 1; // RENAMED MOTOR
for (int i = 0; i < nShields; i++) {
for (int j = 0; j < nMotorsPerShield; j++) {
if (i == shield && j == thismotor) // RENAMED MOTOR
motor[i][j]->run(FORWARD);
else
motor[i][j]->run(RELEASE);
}
}
}
answered Feb 11, 2016 at 23:02
Majenko♦Majenko
104k5 gold badges76 silver badges134 bronze badges
1