Quick C question
markw at mohawksoft.com
markw at mohawksoft.com
Wed Nov 16 14:20:43 EST 2005
> Date: Wed, 16 Nov 2005 10:35:42 -0500 (EST)
> From: Anthony Gabrielson <agabriel at home.tzo.org>
> Subject: Quick C question
> To: discuss at blu.org
> Message-ID: <Pine.BSO.4.56.0511161030130.20031 at home.tzo.org>
> Content-Type: TEXT/PLAIN; charset=US-ASCII
>
> 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?
>
> #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
The above code is prety damn broken. How does the compiler know how big
the arrays are? In a single dimention array, it is just "base + offset" in
a multidimentional array, say foo[X][Y], without any guidence, the
compiler will just assumie you are using this:
int ** array;
Which will have to be initialized like this:
int **array = malloc(D1 * sizeof(int *));
for(int i=0; i < D2; i++)
array[i] = malloc(D2*sizeof(int));
For image processing, I'd abandon the whole two dimentional array and
synthesize it as:
int * array = malloc(D1 * D2 * sizeof(int));
printf("Elem[x][y] = %d\n",array[x*D2 + y]);
More information about the Discuss
mailing list