N
N
nishe2021-12-08 18:21:31
C++ / C#
nishe, 2021-12-08 18:21:31

Am I understanding the program correctly?

I wrote code that creates in memory arrays of pointers to pointers every four numbers entered.
These four numbers are written in four positions or what? Write wrote, but until the end of the meaning of the program did not understand.
The point is that I created an array expanding by rows, which has four columns by condition and write numbers there.

#include <stdio.h> 
#include <locale.h>
#include <iostream>
#include <string>




int main()
{
    setlocale(LC_ALL, "RUS");
    int** A = NULL;
    int number;
    int count = 0;
    while (true)
    {
        A = (int**)realloc(A, ++count * sizeof(int*));

        for (int i = count-1; i < count; i++)
        {
            A[i] = (int*)malloc(4 * sizeof(int));
        }

      
        for (int j = 0; j < 4; j++)
        {
            printf("Введите число ");
            std::cin >> number;
            A[count-1][j] = number;
        }
        
        printf("Введенная вами массив равен \n");
        for (int i = 0; i < count;i++)
        {
            for (int j = 0; j < 4; j++)
            {
                printf("%d ", A[i][j]);
            }
            printf("\n");
        }


    }
    return 0;
}

Input example:
Enter number : 1
Enter number : 2
Enter number : 3
Enter number : 4

Output:
1 2 3 4

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2021-12-09
@nishe

You understand correctly.
The loop is always from one iteration, so there is no point in it. Leave just one memory allocation for the last element of array A (remove the loop itself). At the end you don't free the memory - it's a leak. In real projects, this behavior ends badly. for (int i = count-1; i < count; i++)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question