Click here to Skip to main content
15,910,211 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i tired to write a program to create a 2d array dynamically but its give me error at the run time,please tell me what's the problem here
error : segmetation fault (code dumped)

What I have tried:

#include<iostream>
using namespace std;
int main(){
	int a,b;
	static int**bptr;
	cout<<"Enter the number of row and collumn : ";
	cin>>a>>b;
	bptr=new int*[a];
	for(int i=0;i<a;i++){
		*(bptr+(sizeof(int*)*i))=new int[b];
		for(int j=0;j<b;j++){
			cin>>*(*(bptr+(sizeof(int*)*i))+(sizeof(int)*j));
		}
	}
}
Posted
Updated 7-Aug-17 6:39am
v2

Why have you written such complicated statements? They are bound to cause problems. Just try something like:
C++
for(int i=0;i<a;i++)
    {
    bptr[i] = new int[b];
    for(int j=0;j<b;j++)
            {
        cin>> bptr[i][j];
    }
}
 
Share this answer
 
Your code is misusing pointer arithmetic (see, for instance 6.8a — Pointer arithmetic and array indexing | Learn C++[^]).

Try
C++
#include<iostream>
using namespace std;
int main()
{
  int rows, cols;
  int * * bptr;
  cout<<"Enter the number of rows : ";
  cin >> rows;
  cout<<"Enter the number of cols : ";
  cin >> cols;

  bptr = new int *  [rows];

  for (int r = 0; r < rows; ++r)
  {
    bptr[r] = new int[cols];

    for (int c = 0; c < cols; c++)
    {
      cout << "please enter the value at " << r << ", " << c << endl;
      cin >> bptr[r][c];
    }
  }

  for (int r = 0; r < rows; ++r)
  {
    for (int c = 0; c < cols; ++c)
      cout << bptr[r][c] << "\t";
    cout << endl;
  }

  for (int r = 0; r < rows; ++r)
    delete [] bptr[r];

  delete [] bptr;

}
 
Share this answer
 
The problem is your use of pointer math, which in this case is not needed.

In C/C++ when adding a value to a pointer, the compiler does not add the integer value to the base pointer, but computes the size of the reference item and adds that to the base pointer.

Lets say we have this:
int a[10];
int *p = a;

If we print the value of p (i.e. the memory location that p points to) we might get a value like 0x800. Then if we print the value of (p+1), we do not get 0x801, but in fact get 0x804. The compiler does the calculation of item sizes for you.

So, if we wanted to use p to assign the values 10..19 to array a, above, we can write

C++
for(int i = 0; i < 10; ++i)
    p[i] = i + 10;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900