Code Guru
Code Guru

Reputation: 393

How to get the number of columns of a char array?

Is there a way to get the number of columns a char array has?

It's declared like this: static const char *countries[][2] = { ... };

But I want to get it dynamically, so without typing '2' myself

Upvotes: 1

Views: 173

Answers (2)

Jens Gustedt
Jens Gustedt

Reputation: 78903

Sure you may. Statically initialized arrays can be inspected with the sizeof operator easily. The following snippet (in C) prints all sizes that are assoiated to your 2D array of pointers.

#include <stdio.h>

static const char *countries[][2] = { { "dfdf", "dss" }, { "ss"}, { "toto"}};

int main(void) {
  printf("dim0 %zu, dim1 %zu, elements %zu\n",
         sizeof countries/sizeof countries[0],
         sizeof countries[0]/sizeof countries[0][0],
         sizeof countries/sizeof countries[0][0]
         );
}

Upvotes: 0

Giulio Franco
Giulio Franco

Reputation: 3230

No, you have to pass the size along with the array. There might exist system/compiler/library dependent ways, but it's not a good idea to rely on such functionalities. If you're using the C++ standard library, you'd better use std::vector, which carries more metadata, such as the size() you're interested in.

Upvotes: 1

Related Questions