简体   繁体   中英

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?

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM