coder_mnn's blog

By coder_mnn, history, 4 weeks ago, In English
#include <iostream>
using namespace std;

void make_allocation(int n, int m, int ***ptr){ //where n is row and m is column
	*ptr = new int* [n];
	for(int i = 0; i < n; i++){
		*ptr[i] = new int[m];
	}
}

int main() {
	int n,m;
	cin>>n>>m;
	int **ptr = NULL;
	make_allocation(n,m, &ptr);
	for(int i=0;i<n;i++)for(int j=0;j<m;j++)ptr[i][j] = i+j;
	for(int i=0;i<n;i++)for(int j=0;j<m;j++)cout<<ptr[i][j]<<" ";
	return 0;
}
 
 
 
 
  • Vote: I like it
  • 0
  • Vote: I do not like it

»
4 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by coder_mnn (previous revision, new revision, compare).

»
4 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

*ptr[i] parses as *(ptr[i]) rather than as (*ptr)[i], so your for loop in make_allocation is performing some illegal accesses.

  • »
    »
    4 weeks ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thanks clyring, Now understood. I have to change *ptr[i] as (*ptr)[i]

»
4 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

maybe you can write the above make_allocation function like this void make_allocation(int n,int m, int ***ptr){ int **temp=new int*[n]; for(int i=0; i<n; i++) { temp[i]=new int[m]; } *ptr=temp; }

  • »
    »
    4 weeks ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Yes, it's working. But we have to avoid extra pointer.