O
O
Ogurchik-0072022-03-15 16:26:29
C++ / C#
Ogurchik-007, 2022-03-15 16:26:29

Why are numbers not in the specified range written to the array?

I wrote the code, the elements of the array must be set randomly in the specified range, but when the array is displayed, the numbers are random.

#include<iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;

void inputArray(int *p, int k); // Функция инициализации массива

void printArray(int B[14][24], int i, int j) { // Функция для вывода массива
  for (i = 0; i < 24; i++) {
    for (j = 0; j < 14; j++) {
      cout<<setw(5)<<B[i][j];
    } 
    cout<<endl;
  }
}

void processingArray(int *B[0], int k, int i, int j) { // Функция для обработки массива 
  for (i = 0; i < 24; i++) {
    for (j = 0; j < k; j++) {
      if (B[i][j] > 0) {
        B[i][j] = 0;
      }
      else {
        B[i][j] = B[i][j] * -10;
      } 
    } 
  };
}

int main() {
  setlocale(LC_ALL, "Russian");
  const int n = 14;
  const int m = 24;
  int B[n][m], i=0, j=0;


  
  
  for(i = 0; i < n; i++){
  	inputArray(B[i], m);
  	for (j = 0; j < m; j++){
  		cout<<setw(12)<<B[i][j];
    }
  cout<<endl;
  }

  cout<<endl<<endl;
  

  
  

}

void inputArray(int *p, int k) {
  srand(time(0));
  *p = (rand( )%100 - 50);
  for (int i = 1; i < k; i++) {
    *(p + i) = -i * * (p + i - 1);
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2022-03-15
@wataru

*p = (rand( )%100 - 50);
for (int i = 1; i < k; i++) {
  *(p + 1) = -i * * (p + i - 1);
}

Can you please explain what this code does? Why is he doing this? What did you want him to do? In addition, you can write
instead . So it's clearer. At you here obviously not to a place the arithmetic of pointers is woven. And so, the code works as it is written. The first number in the array is filled with a random number from -50 to 49, the second number is overwritten many times with something multiplied by some other number in the array, the rest of the numbers are not filled at all. Since your array is local, it is not initialized with zeros. Therefore, there is initially random garbage. Therefore, everything except the first element will be random garbage. *(p+X)p[X]

R
Rsa97, 2022-03-15
@Rsa97

You fill only p[0] and p[1], the rest of the array cells remain uninitialized.
Apparently, you crookedly typed the text from some video tutorial, and instead of * (p + i) wrote * (p + 1).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question