Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   pointers (http://www.go4expert.com/forums/pointers-t3862/)

 sunil_ghai 14Apr2007 14:35

pointers

members plz help me..
while defining 2D array through pointers we must know the maximum limit of one expression like:
int *ptr[x],here x should be known and we can further allocate the memory through malloc function.
can anyone plz tell me how can we define a pointer in which both limits can be entered by user?

 DaWei 14Apr2007 19:53

Re: pointers

The C99 standard allows for run-time assignment of array dimensions, but few compilers are compliant in that respect. Consequently, we fake it. Suppose we want a 2D array of dimensions m x n. We ask malloc to give us memory for m pointers to the element type. We then ask malloc to give us memory for n elements. We store the pointer to that memory in the first array. We then repeat that second request until we have done it m times, storing each of those pointers in the first array.

This gives us m pointers to arrays containing n elements. Job done. Understand that this is not a true 2D array, in that it is not all contiguous, but it gives us a means of addressing any element, given a value for m and a value for n.

Take a shot at implementing that. If you have problems, please post back.

 wrecker 15Apr2007 14:40

Re: pointers

int **p;
p=(int **)malloc(m*n*sizeof(int));
m and n are the rows and columns .....
this is how you have to allocate memory to 2D array. No one max limit is needed.....

 DaWei 15Apr2007 16:39

Re: pointers

Wrecker, that is not correct. In your code, p is a pointer to an integer pointer. Dereferencing it will provide a value that is expected to be a pointer to an integer, not an integer. One can allocate the entire array in one swoop, as you show, but one can not then access it in 2D fashion, except by performing arithmetic manipulations involving multiplications by m.

 wrecker 20Apr2007 01:48

Re: pointers

Quote:
 Originally Posted by DaWei Wrecker, that is not correct. In your code, p is a pointer to an integer pointer. Dereferencing it will provide a value that is expected to be a pointer to an integer, not an integer. One can allocate the entire array in one swoop, as you show, but one can not then access it in 2D fashion, except by performing arithmetic manipulations involving multiplications by m.
Hey DaWei, actually the code posted works very fine and to tell you that this was the code used when i had won the national level programming competition. Also i didnot understaand why cant we access it in 2D fashin. I dont mean to say that M the only one who is correct but To the best of my knowledge m correct and code also......

 DaWei 20Apr2007 02:45

Re: pointers

I invite you to write your code and add a line where you attempt to store an integer at p[m][n] (that would be 2D array notation) for some valid value of m and n.

 All times are GMT +5.5. The time now is 07:39.