user4075334
user4075334

Reputation:

Size of 2d array in c

I have a 2d array represented as double pointer- `

   char ** arr;
  arr = (char **) malloc(100 * sizeof(char *));
    for (i=0; i<100; i++)
         arr[i] = (char *) malloc(3 * sizeof(char));

Now I have 100 rows and 3 columns in arr.But this array is used somewhere else which fills far less rows than 100.So how can I get the size(number of rows filled) in order to print this array???

Upvotes: 0

Views: 178

Answers (2)

unwind
unwind

Reputation: 399803

You can't, you're going to have to use a more expressive representation that can hold such meta information.

Memory is memory, there's no way to determine if it has been "used" or not, since it's there all the time once you've allocated it.

If you can't use the sentinel approach (like C strings, have a terminator indicate end-of-valid-data) you're going to have to use explicit length values or some other approach that expresses this.

Also, please don't cast the return value of malloc() in C.

Further, don't scale allocations by sizeof (char) since that's always 1 you're only adding noise. This is, quite obviosuly, my opinion. Your code will never be technically wrong if it includes that multiplication, and some clearly feel that it adds value and makes the code clearer.

Finally, you are doing 100 heap-allocations of 3 bytes each, that is very inefficient. I would suggest just doing an array of 100 3-byte arrays (possibly expressed as an array of structs).

Upvotes: 2

Lundin
Lundin

Reputation: 213711

I have a 2d array represented as double pointer

No you don't. You have a pointer-to-pointer based lookup table. To dynamically allocate multi-dimensional arrays, do something like this. Also see How do I correctly set up, access, and free a multidimensional array in C?.

But this array is used somewhere else which fills far less rows than 100.So how can I get the size(number of rows filled) in order to print this array???

Have your application keep track of it. There is no other way. sizeof etc won't work, not even if you use a proper array instead of a lookup table. Because sizeof knows nothing about the contents of the array. The best and simplest solution is to keep a separate size counter variable.

If you for some reason can't use such a size counter, you could make something more complex. Surround the code filling in values with some wrapper API. Then suppose for example that you allocate 101 items instead of 100 and use either the first or last item to contain the size. You'll have to clear all memory cells if you use such a method, so preferably use calloc instead of malloc in that case.

Or possibly make a linked list implementation if you need to add/remove items in the middle.

Upvotes: 0

Related Questions