1

Ok so i have written this code to print all elements of an 2D array . But , surprisingly , nothing is printed on the screen. Here's the code:

#include <bits/stdc++.h>
using namespace std;

char ans[1001][1001];



void display_ans(int row,int col)
{
    for (int i=0;i<row;i++)
    {
        for(int j=0;j<col;j++)
        {
            cout<<ans[i][j];
        }
        cout<<endl;
    }
}

int main()
{
    memset(ans,'$',sizeof(ans[0][0])*2*2);
    display_ans(2,2);
    return 0;
}

There is nothing printed on the screen.This is really awkward.I cant understand whats wrong with the code.

Piyush Soni
  • 197
  • 2
  • 10

1 Answers1

4

Lets take a look at a somewhat smaller array of arrays look like in memory:

char a[3][3];

This will be something like

+---------+---------+---------+---------+---------+---------+---------+---------+---------+
| a[0][0] | a[0][1] | a[0][2] | a[1][0] | a[1][1] | a[1][2] | a[2][0] | a[2][1] | a[2][2] |
+---------+---------+---------+---------+---------+---------+---------+---------+---------+

A call like memset(ans,'$',sizeof(ans[0][0])*2*2); will set the memory for the four first memory locations. That is with our example above it will be a[0][0], a[0][1], a[0][2] and a[1][0]. The memory for e..g a[2][1] will not be touched.

For your array, ans[0][0] is the first element, followed by ans[0][1], and all the remaining 999 elements of a[0] before a[1][0].

That leads to the elements that will be set by your memset call will be ans[0][0], ans[0][1], ans[0][2] and ans[0][3]. The rest of the memory for ans will be all zero.

And since you print using one-based indexes, you print ans[1][1], ans[1][2], ans[2][1] and ans[2][2]. Which are all zero.


Oh I see that you updated your question, which means you will print ans[0][0], ans[0][1], ans[1][0] and ans[1][1]. The first two characters should be '$', while the second two will still be zero.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 2
    all that OP had to write is `memset(ans, '$', sizeof(ans) );` – Swift - Friday Pie Feb 06 '18 at 14:18
  • 1
    @Swift Well since it's C++ I would rather recommend e.g. `std::fill_n(&ans[0][0], sizeof ans , '$');` :) – Some programmer dude Feb 06 '18 at 14:20
  • 1
    I did not said that he SHOULD have write this, although for some C++ imlementations memset used on char array is still the fastest way to do this (fill is significantly slower). All i hinted at is that OP code looks like an example of overcomplication caused by misconstrued view or ignorance. I totally agree otherwise – Swift - Friday Pie Feb 06 '18 at 14:28
  • Its working fine now. I just replaced the sizeof(ans)*2*2 by sizeof(ans).Thanks. – Piyush Soni Feb 07 '18 at 13:50