2

I tried initializing a dynamically allocated (2D?) array as all is (i>0) using memset. But then , when I am printing out the values of the array, it is printing some garbage. Following is my code snippet:

int main() {
    int T=1, R=3, C=3;
    int **grid = new int*[R], *temp = new int[R*C];
    for (int i=0; i<R; i++)
        grid[i] = (temp+(C*i));
    for (int t=1; t<=T; t++){
        memset(temp,1,sizeof(int)*R*C);
        cout << t << ":\n";
        for (int i=0; i<R; i++){
            for (int j=0; j<C; j++)
                cout << grid[i][j] << " ";
            cout << endl;
        }
    }
    delete [] grid;
    delete [] temp;
    return 0;
}

And the following is the output:

1:
16843009 16843009 16843009
16843009 16843009 16843009
16843009 16843009 16843009

But, if I try to initialize it with 0, it works fine and displays:

1:
0 0 0
0 0 0
0 0 0

I am relatively new to learning C++. What is going wrong with the code?



KamilCuk
  • 120,984
  • 8
  • 59
  • 111
Python_user
  • 1,378
  • 3
  • 12
  • 25

1 Answers1

3

memset writes to every byte not to every int in the array.

The value 16843009 in hex is 0x01010101 an int with 4 bytes each of them set to 1.

memset will operate on bytes, there is no way to make it operate on integers.

Szabolcs Dombi
  • 5,493
  • 3
  • 39
  • 71
  • 1
    Thanks! So, is there any way to initialize the array to all 1s (other than using memset OR looping through all the elements and setting them to 1)? – Python_user Oct 27 '18 at 07:43
  • 2
    @Python_user yes. [A method to assign the same value to all elements in an array](https://stackoverflow.com/q/8421846/995714) – phuclv Oct 27 '18 at 09:21