9

I'd like to know how to get an array rows & columns size. For instance it would be something like this:

int matrix[][] = { { 2, 3 , 4}, { 1, 5, 3 } }

The size of this one would be 2 x 3. How can I calculate this without including other libraries but stdio or stdlib?

4 Answers 4

17

This has some fairly limited use, but it's possible to do so with sizeof.

sizeof(matrix) = 24  // 2 * 3 ints (each int is sizeof 4)
sizeof(matrix[0]) = 12  // 3 ints
sizeof(matrix[0][0]) = 4  // 1 int

So,

int num_rows = sizeof(matrix) / sizeof(matrix[0]);
int num_cols = sizeof(matrix[0]) / sizeof(matrix[0][0]);

Or define your own macro:

#define ARRAYSIZE(a) (sizeof(a) / sizeof(a[0]))

int num_rows = ARRAYSIZE(matrix);
int num_cols = ARRAYSIZE(matrix[0]);

Or even:

#define NUM_ROWS(a) ARRAYSIZE(a)
int num_rows = NUM_ROWS(matrix);
#define NUM_COLS(a) ARRAYSIZE(a[0])
int num_cols = NUM_COLS(matrix);

But, be aware that you can't pass around this int[][] matrix and then use the macro trick. Unfortunately, unlike higher level languages (java, python), this extra information isn't passed around with the array (you would need a struct, or a class in c++). The matrix variable simply points to a block of memory where the matrix lives.

Sign up to request clarification or add additional context in comments.

1 Comment

@BlueRaja, true. I was thinking of using a class or vector<>... but I guess you might as well use a struct in c. Edited.
5

It cannot be "something like this". The syntax that involves two (or more) consecutive empty square brackets [][] is never valid in C language.

When you are declaring an array with an initializer, only the first size can be omitted. All remaining sizes must be explicitly present. So in your case the second size can be 3

int matrix[][3] = { { 2, 3, 4 }, { 1, 5, 3 } };

if you intended it to be 3. Or it can be 5, if you so desire

int matrix[][5] = { { 2, 3, 4 }, { 1, 5, 3 } };

In other words, you will always already "know" all sizes except the first. There's no way around it. Yet, if you want to "recall" it somewhere down the code, you can obtain it as

sizeof *matrix / sizeof **matrix

As for the first size, you can get it as

sizeof matrix / sizeof *matrix

Comments

0

sizeof (matrix) will give you the total size of the array, in bytes. sizeof (matrix[0]) / sizeof (matrix[0][0]) gives you the dimension of the inner array, and sizeof (matrix) / sizeof (matrix[0]) should be the outer dimension.

Comments

0

Example for size of :

#include <stdio.h>
#include <conio.h>
int array[6]= { 1, 2, 3, 4, 5, 6 };
void main() {
  clrscr();
  int len=sizeof(array)/sizeof(int);
  printf("Length Of Array=%d", len);
  getch();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.