On Sun, May 25, 2008 at 09:38:38PM +0000, Antoninus Twink wrote:
On 25 May 2008 at 20:44, Aggelidis Nikos wrote:
On Sun, 25 May 2008 20:30:08 +0000, Antoninus Twink wrote:
Create your array on the heap with malloc() instead, protect accesses to
it using a mutex, and decide for yourself when the right time is to
free() it.
but vla's where introduced to solve numeric problems.
What do you mean? The only possible advantage I can think of of a VLA is
Well, if the OP wants variable length arrays, let's do that, he might
have a good reason: e.g. he has a well tested set of routines for vlas,
and he is trying to port it to a multicore system.
Posix threads are not standard C, but let's not cancel the discussin at this
point. Posix threads allow one single void* to pass to a function executed
in a separate thread. The OP wants now to use this to pass a vla.
One typically creates a struct that contains all the desired data to pass,
and one gives the pointer to this struct (converted to void*) to
pthread_create().
If the question was about a one-dimensional array, I'd suggest the flexible
array member. With two dimensions, I'd better let the OP declare the array
in the main, and put a pointer to it (or the its first subarray) into the
sturct of parameters.
Let me show an example:
#include <stdio.h>
#include <pthread.h>
struct parameters {
int n;
void *array;
};
void* thread(void*P)
{
int n=((struct parameters*)P)->n;
double (*A)[n]=((struct parameters*)P)->array;
/* now you have n and A exactly as if you had a prototype, like
thread(int n,double A[n][n])
*/
for(int i=0;i<n;i++,puts("")) for(int j=0;j<n;j++) printf("%g ",A[i][j]);
return NULL;
}
int main()
{
int n=4;
double A[n][n];
for(int i=0;i<n;i++) for(int j=0;j<n;j++) A[i][j]=10*i+j;
struct parameters P={.n=n,.array=(void*)A[0]};
pthread_t T;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&T,&attr,thread,&P); /* error checking ... */
pthread_join(T,NULL);
}
Szabolcs