Acess Violation 2d array @ debug

My program compiles without errors but when i debug my program i get the error message "Unhanded exception at 0x0131175c in test.exe: 0xC0000005: Access violation writing location 0xcdcdcdcd." I have tracked the problem to my array cxP which i think is well initialized. I cant semm to get beyond this. any help. I am using VS 2010. This is not the entire program but a test piece that reproduces the problem in the bigger program. Actually all my 2d arrays are failing for some reason i dont understand.

HELP PLEASE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream> //enables output & input
#include <fstream>
#include <string>
#include <algorithm>
#include <stdio.h>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
using namespace std;

void Isort(int*fn,int nN) {//increasing integers sort

	int ftemp;
	for (int c=0;c<nN;c++)// to represent element to be compared
	{
		for (int j=(c+1);j<nN;j++)// to represent the rest of the elements
		{
			if (fn[c] > fn[j])
			{
				ftemp= fn[c];    // swap  objective function    
				fn[c] = fn[j];
				fn[j] = ftemp;
			}
		}
	}}

int main()
{
		int *x;x=new int [5];
		for(int i=0;i<5;i++){x[i]=5-i;}
		for(int i=0;i<5;i++){cout<<x[i]<<"\t";}
		cout<<"\n";
		Isort(x,5);
		for(int i=0;i<5;i++){cout<<x[i]<<"\t";}
		int npg=31;
		int ngs=35;cin.get();
		
		int **cxP; 
		cxP=new int*[npg];
		for(int i=1;i<npg;i++){cxP[i]=new int[ngs];}//cxinP[npg][ngs]

		for(int ipg=0;ipg<npg;ipg++){
			for(int igs=0; igs<ngs;igs++){
				cxP[ipg][igs]=0;}}
		cin.get();
}
Hello ejjunju,

This line
for(int i=1;i<npg;i++){cxP[i]=new int[ngs];}//cxinP[npg][ngs]
starts with 1 (i=1) so the first element remains uninitilized

I's suggest that you don't use 2d arrays but instead 1d and calculating the offset yourself. That might be easier to handle and does not require this enless row of new's
Thank you for pointing that out. I am not so sure I understand the offset suggestion. You see i have to generate a population of random numbers here cxP[ipg][igs]=0 that i use in an optimization process that requires the sorting of the entire population and divinding it into groups that are later handled one by one and when the process is done, must be replaced in the original array.
well, consider the following

2d solution:
1
2
3
4
5
6
7
8
  enum { x_size = 5, y_size = 32 };

  char buf[x_size][y_size];

  int x = 2;
  int y = 3;

  buf[x][y] = '1';


1d solution:
1
2
3
4
5
6
7
8
  enum { x_size = 5, y_size = 32 };

  char buf[x_size * y_size];

  int x = 2;
  int y = 3;

  buf[(x * y_size) + y] = '1';


the 1d solution might look more complicated but with dynamic allocation and parameter passing it's much easier to handle
Thanks!! They should add "Like" buttons to this forum.
Topic archived. No new replies allowed.