Boston Linux & Unix (BLU) Home | Calendar | Mail Lists | List Archives | Desktop SIG | Hardware Hacking SIG
Wiki | Flickr | PicasaWeb | Video | Maps & Directions | Installfests | Keysignings
Linux Cafe | Meeting Notes | Blog | Linux Links | Bling | About BLU

BLU Discuss list archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Quick C question



On Wed, Nov 16, 2005 at 10:35:42AM -0500, Anthony Gabrielson wrote:
> Hello,
> 	I'm trying to some image processing in C and I won't know ahead of 
> time what the dimensions of the image are.  So I would like to do a 
> multi-dim array with a pointer so I can malloc the space and hopefully be 
> good.  The problem is that the compiler doesn't seem to agree with this 
> strategy. So does anyone have an idea of how to do something like the 
> attached example with pointers by chance?

Arrays are one-dimensional beasts - unless you know something that can
give the compiler a hint (like the size of all but the last dimension)
at compile-time, you're going to need to manage this is an array of
array pointers.

int n, **array;
array = (int **)malloc(sizeof(int *) * D1);
for (n = 0; n < D1; n++) {
  array[n] = (int *)malloc(sizeof(int) * D2);
}
. . .
. . .
. . .
for (n = 0; n < D1; n++) {
  free(array[n]);
}
free(array);


Nathan


> 
> #include <stdio.h>
> 
> #define	D1	4
> #define	D2	2
> 
> int main(){
> 
> 	int *array;
> 
> 	array = malloc(sizeof(int) * (D1 * D2));
> 
> 	array[1][1] = 32;
> 
> 	printf("Elem[1][1] = %d\n",array[1][1]);
> 	
> 	free(array);
> 
> 	return 0;
> }
> 
> Thanks,
> Anthony
> _______________________________________________
> Discuss mailing list
> Discuss at blu.org
> http://olduvai.blu.org/mailman/listinfo/discuss
> 




BLU is a member of BostonUserGroups
BLU is a member of BostonUserGroups
We also thank MIT for the use of their facilities.

Valid HTML 4.01! Valid CSS!



Boston Linux & Unix / webmaster@blu.org