John Doe
John Doe

Reputation: 195

How to get an array size

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?

Upvotes: 9

Views: 25298

Answers (4)

Stephen
Stephen

Reputation: 49234

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.

Upvotes: 17

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

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

Upvotes: 5

Karthik
Karthik

Reputation: 3301

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();
}

Upvotes: 0

Alexander Gessler
Alexander Gessler

Reputation: 46677

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.

Upvotes: 0

Related Questions