Ошибка сегментации внутри, но не знаете, как ее исправить. - PullRequest
0 голосов
/ 13 апреля 2020

В настоящее время пытаюсь поработать над этим кодом, чтобы найти ошибки и как их исправить, и впервые научиться использовать GDB,

int Find11();
void PointersAreFun();

int main(void) {
  int myArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
  int found = Find11();
  if (found != -1) {
    printf("The number 11 is in the table at location: %d\n", found);
  } else {
    printf("The number 11 is not in the table.\n");
  }

  PointersAreFun(myArray, 10);
  return 0;
}

int Find11(void) {
  int i = 0;
  int count = 0;
  int search = 1;
  int found = -1;
  int number = 5;
  int table[10];

  table[0] = number;
  printf("table[%i]: %i\n", count, table[count]);

  count = 1;
  while (count < 10) {
    table[count] = number++ * 2;
    printf("table[%i]: %i\n", count, table[count]);
    count++;
  }
  while (search = 1) {
    if (table[i++] == 11) {
      search = 0;
      found = -1;
    }
    if (count == i) {
      search = 0;
      found = 0;
    }
  }
  return found;
}

void PointersAreFun(int myArray[], int size) {
  printf("\nDemo on Pointers!\n");
  int anotheArray[10] = {10, 11, 12};
  int *ptrArray = NULL;
  int *ptrAnotherArray = NULL;
  ptrArray = myArray;
  printf("The first value of the array is %d\n", *ptrArray);
  printf("The first value of the second array is %d\n", *ptrAnotherArray);
}

Я обнаружил ошибку сегментации вокруг этого блока кода

  while (search = 1) {
    if (table[i++] == 11) {
      search = 0;
      found = -1;
    }
    if (count == i) {
      search = 0;
      found = 0;
    }
  }

но я не уверен, как решить проблему, так как кажется, что переменная i продолжает увеличиваться бесконечно, пропуская if (count == i), как в отладчике GDB, даже если count равен 10 и переменная я равняюсь 10, это продолжает увеличиваться. Пропуск второй, если условие

1 Ответ

2 голосов
/ 13 апреля 2020

в вашем коде:

while( search = 1 )

Вы должны использовать == для сравнения search с 1

Еще одна вещь

int * ptrAnotherArray = NULL;
printf("The first value of the second array is %d\n", *ptrAnotherArray);

Вы устанавливаете указатель == NULL, а затем печатаете значение, на которое он указывает. Это делает segt вина

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