I tried initializing a dynamically allocated (2D?) array as all i
s (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?
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.