D
D
Daniil Igorevich2016-06-17 19:46:43
C++ / C#
Daniil Igorevich, 2016-06-17 19:46:43

Why is the array filled with the letter H?

#include <iostream>;
#include <conio.h>;
#include <ctime>;

using namespace std;


int main() {
  setlocale(0, "");
  
  char **arr = new char*[10];

  for (int i = 0; i < 10; i++) {
    arr[i] = new char[10];
  }

  arr[0][1] = 'K';
  arr[0][2] = 'L';

  for (int i = 0; i < 10; i++) {
    for (int z = 0; z < 10; z++) {
      cout << arr[i][z] << endl;
    }
  }

  system("pause");
  return 0;
}

fe7be62c95a44efb942911974454203a.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Zhilin, 2016-06-17
@Anton3

The memory is not initialized, so there is garbage. What exactly is Unspecified Behavior.

A
Alexander Movchan, 2016-06-17
@Alexander1705

In general, this is rather strange, no unspecified behavior should occur, since the new expression calls the default constructor for each object, that is, built-in types must be initialized to zero .
Try to display not a symbol, but its code, replacing one line with:
Secondly, endl not only translates to a new line, but also resets the accumulated buffer, that is, immediately displays everything on the screen or in a file. If you have a lot of output, this can seriously slow down your program. For a simple newline, output a special control character'\n'
If you output a matrix (two-dimensional array), it is more convenient to do it like this:

for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        cout << arr[i][j] << ' '; // пробел можно убрать
    }
    cout << '\n';
}

Also, you should never use the system. It pauses your program and starts another one (in this case pause). This option is not only not optimal, but also platform-dependent. People who use mac or linux will have to make changes to your code in order to run it, since these OSes do not have the pause. Use the C++ language tools for this: cin.get();
And never use the conio.h header file again . It is not part of the C or C++ language standard, and is not supported by most compilers.
PPS What compiler are you using? What version is it? What are the compilation keys or project settings in the IDE?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question