1

I've created a dynamic 2-d array, but I don't know how to use memset in that? Here's a piece of my code-

ll **arr;
arr = new ll*[n];
for(int i=0; i<n; i++){
    arr[i] = new ll[x];
}

I'm doing memset(arr, -1, ((n*x))* sizeof(*arr)) but it is not working. can anyone help?

  • You have no two-dimensional array. You have one-dimensional array of pointers that point to another one-dimensional arrays. So you have to apply memset to each pointed array separately. – Vlad from Moscow Apr 10 '20 at 18:18
  • Instead of creating your arrays the way you did, you can do it [this way](https://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048), in a contiguous manner. Then `memset` will work (once you give it the right parameters). Also, please don't use those macros from another world, like `ll`. It just obfuscates the code. – PaulMcKenzie Apr 10 '20 at 18:19

1 Answers1

0

You did not allocate a two-dimensional array. You allocated a one-dimensional array of pointers each of them points to a one-dimensional array of elements of the type (as I suppose) long long int.

So you need to call memset for each such an allocated one-dimensional array separately.

Here is a demonstrative program.

#include <iostream>
#include <cstring>

int main() 
{
    size_t n = 0;

    std::cout << "Enter the size of a matrix: ";

    if ( std::cin >> n && n != 0 )
    {
        long long int **a = new long long int * [n];

        for ( size_t i = 0; i < n; i++ )
        {
            a[i] = new long long int [n];
            std::memset( a[i], -1, n * sizeof( long long int ) );
        }

        for ( size_t i = 0; i < n; i++ )
        {
            for ( size_t j = 0; j < n; j++ )
            {
                std::cout << a[i][j] << ' ';
            }
            std::cout << '\n';
        }

        for ( size_t i = 0; i < n; i++ )
        {
            delete [] a[i];
        }
        delete [] a;
    }

    return 0;
}

Its output might look like

Enter the size of a matrix: 5
-1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 

The program will work for the 2 complement internal representation of integers.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335