tags:

views:

67

answers:

2

I am trying to allocate a 2D dimension array of File Descriptors... So I would need something like this fd[0][0] fd[0][1]

I have coded so far:

void allocateMemory(int row, int col, int ***myPipes){
    int i = 0,i2 = 0;
    myPipes = (int**)malloc(row * sizeof(int*));
    for(i = 0; i < row;i++){
       myPipes[i] = (int*)malloc(col * sizeof(int));
    }
  }

How can I set it all too zeros right now I keep getting a seg fault when I try to assign a value...

Thanks

+2  A: 

So, first, you're going to have to pass in a pointer to myPipes:

void allocateMemory(int rows, int cols, int ***myPipes) { ... }

Then it's easy:

*myPipes = malloc(sizeof(int) * rows * cols);

And of course, you'd call it with:

int **somePipes;
allocateMemory(rows, cols, &somePipes);
David Wolever
+2  A: 

short answer: change your innermost malloc to a calloc.

long answer provided by the c faq: http://c-faq.com/~scs/cclass/int/sx9b.html

What you need to understand is that C doesn't really have a way to allocate a true multidimensional array. Instead, you just have a pointer to an array of pointers. Treat your data structure as such and you will be fine.

frankc
Perfect Thanks!
Jacob