Alex Rivera | Logout

initialize a multidimensional C array of variable size to zero

Asked 2010-09-15T14:41:07.907
11

I want to initialize a two-dimensional array of variable size to zero. I know it can be done for a fixed-sized array:

int myarray[10][10] = {0};

but it is not working if I do this:

int i = 10;
int j = 10;
int myarray[i][j] = {0};

Is there a one-line way of doing this or do I have to loop over each member of the array?

Thanks

Edit
Report

2 Answers

1

If you get a pointer to your data structure, you could try memset.

answered 2010-09-15T14:47:01.427
0

You can't create a static array using non-constant variables. Try using dynamic allocation:

int i = 10;
int j = 10;
size_t nbytes = i*j*sizeof(int);
int* myarray = (int*) malloc(nbytes);
memset(myarray,0,nbytes);
answered 2010-09-15T14:59:13.313

Your Answer