user5335769
user5335769

Reputation:

Getting the Outer-array length in C

To get array length I can (usually) do:

sizeof(array) / sizeof(array[0])

What about if it's a multidimensional array, such as:

{"my", "favorite", "things"}

How would I get the length (3) of that? Basically, the length of the outer-most array.

How is the "end" of the multi-array detected (similar to \0)?

Upvotes: 0

Views: 146

Answers (2)

the busybee
the busybee

Reputation: 12600

You can get the size of each dimension if you use the quotient of the appropriate, well, dimension:

#include <stdio.h>

int main(void) {
  int array[23][42][7];
  unsigned int size_1 = sizeof array / sizeof array[0];
  unsigned int size_2 = sizeof array[0] / sizeof array[0][0];
  unsigned int size_3 = sizeof array[0][0] / sizeof array[0][0][0];
  unsigned int size_e = sizeof array[0][0][0];

  printf("Size of 1st dimension: %u\n", size_1);
  printf("Size of 2nd dimension: %u\n", size_2);
  printf("Size of 3rd dimension: %u\n", size_3);
  printf("Size of element:       %u\n", size_e);

  return 0;
}

The output is:

Size of 1st dimension: 23
Size of 2nd dimension: 42
Size of 3rd dimension: 7
Size of element:       4

There is no "end marker" on arrays in general. You need to track the size if you use dynamically allocated arrays.

The end-of-string marker \0 does not mark the end of the char array but the end of the string. The array can be of any size.


Additional notes, not necessarily perfectly worded in the view of the standard's watchmen ;-)

  1. The sizeof operator is a (kind of) unary operator for the expression following it. It used to be used with types, so a cast can be given:

    sizeof (int)

    This habit led to the feeling that the parentheses are needed, and that it is a kind of function. No, it is not. The result will be calculated by the compiler, and therefore it must be calculatable at compile time.

    If you use it with an object like a variable, you could simply write:

    sizeof variable

  2. If you have a char array at the (second) most inner dimension you would probably liek to call strlen() on each of them. This might apply also to char* as element type.

Upvotes: 1

Eliyahu Machluf
Eliyahu Machluf

Reputation: 1401

The array you've showed is a pointers array:

 char *array = {"my", "favorite", "things"}

you can use the same syntax of

sizeof(array)/sizeof(array[0]) 

to get the number of items at array, which are the number of pointers at array.

Upvotes: 0

Related Questions