индекс вне границ - C # - PullRequest
       2

индекс вне границ - C #

0 голосов
/ 26 ноября 2011

ОК, я пытался сам пройти код несколько раз, но IDE-Visual Studio всегда говорит, что это неправильно ..

УКАЗАТЕЛЬ БЫЛ ВНЕ ОШИБОК ОБЩЕЙ СВЯЗИ

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //declare Arrays for buttons and 
            //LEDs

            int[] buttonArray = new int[4]; // Left to right .-..   ------ 
            //left, top, bottom, right
            int[,] ledArray = new int[10, 10];

            //declare variables
            int strandSnake = 0;
            int requestR = 0;

            int countDeclareButtonArray = 0;
            int countWriteButtonArray = 0;



            //code
            if (strandSnake != 1)
            {

            }


            //Declaring the four buttons
            for (int ip = 0; ip < 4; ip++)
            {
                buttonArray[countDeclareButtonArray] = countDeclareButtonArray;
                countDeclareButtonArray++;
            }

            // writing the four buttons to the screen.

            foreach (int ip in buttonArray)
            {

                requestR = buttonArray[countWriteButtonArray];
                countWriteButtonArray++;
            }

            Console.ReadLine();
        }
    }
}

Ответы [ 2 ]

0 голосов
/ 26 ноября 2011

Посмотрите на фрагмент кода, значение переменной countWriteButtonArray равно 4, поэтому вам нужно присвоить 0 countWriteButtonArray.

countWriteButtonArray=0;
foreach (int ip in buttonArray) 
{
  requestR = buttonArray[countWriteButtonArray];
  countWriteButtonArray++;
}

Если вы хотите получить элемент из массива buttonArray, вы можете использовать:

 foreach (int ip in buttonArray) 
    {
       //
    }

Используйте цикл for для итерации массива с использованием индекса.

for(countWriteButtonArray=0;countWriteButtonArray<=buttonArray.GetUpperBound(0);countWriteButtonArray++) 
    {
      requestR = buttonArray[countWriteButtonArray];
    }
0 голосов
/ 26 ноября 2011

Вы должны знать диапазон индекса массива в C # от 0 .. array.Length - 1

Итак, если у вас есть

int[] a = new int[4];

Вы можете получить доступ а [0].a [1], a [2], a [3] ,

Но при доступе к a [4] вы получите УКАЗАТЕЛЬ БЫЛ ВНЕ ГРАНИЦЫОШИБКА .

Отладка и поиск, откуда произошла ошибка

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...