I am using Visual Studio Community 2017.
Following the discussion below:
Fastest way to zero out a 2d array in C?
I have a 2 D matrix (10 x 10) that I initialize using memset
. This is option 1.
Option 2 is initializing the same matrix using two for
loops, each looping from 0 through 9.
Then, when I write to a valid matrix location, an access violation writing error is thrown when Option 1 was used. Everything works fine when Option 2 is used.
The minimal working code I have that replicates this is given below:
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
#include <math.h>
#include <cmath>
#include <vector>
#include <string>
#include <limits.h>
#include <stdlib.h>
#include <array>
int main(){
double ** cmatrix = new double*[10];
for (int i = 0; i < 10; i++)
cmatrix[i] = new double[10];
memset(cmatrix, 0, 10 * 10 * sizeof(double));//Option 1
//for (int i = 0; i < 10; i++)//Option 2
//for (int j = 0; j < 10; j++)
//cmatrix[i][j] = 0;
cmatrix[0][1] = 5;//This step produces error on Option 1, but not on option 2
return 0;
}
Any help is appreciated.