0

I want to declare an two dimension array, but I don't know first dimension. Second dimension is known.

How do I declare the array?

I found one syntax:

int (*p) [5];

Is it correct syntax? But I do not understand this syntax.

Jeyaram
  • 9,158
  • 7
  • 41
  • 63

3 Answers3

0

You have to use dynamic memory ;)...

#include <stdlib.h>
#include <stdio.h>

#define KNOWN_DIMENSION 16

int main() {
    size_t unknownDimension = rand() % 32 + 1;

    int **dynamic = malloc(unknownDimension * sizeof(int*));
    if(dynamic == NULL) {
        fprintf(stderr, "Unable to allocate\n");
        return -1;
    }

    for(size_t i = 0; i < unknownDimension; i++) {
        dynamic[i] = malloc(KNOWN_DIMENSION * sizeof(int));
        if(dynamic[i] == NULL) {
            fprintf(stderr, "Unable to allocate\n");
            return -1;
        }
    }

    // `dynamic` is usable as an `int[unknownDimension][KNOWN_DIMENSION]` here!

    for(size_t i = 0; i < unknownDimension; i++)
        free(dynamic[i]);

    free(dynamic);
    return 0;
}

BTW: int (*p)[5] is the same as a pointer to int p[5].

3442
  • 8,248
  • 2
  • 19
  • 41
0
int (*p) [5];

means "p is a pointer to an array of five ints".
This pointer can be a pointer to the first element of an array in the normal way.

If you have an array whose elements are five-element arrays of ints, you can use the normal array-to-pointer conversion:

int array[10][5] = {};
int (*p)[5] = array;

or

int (*p)[5] = &array[0];

You can of course also allocate dynamically, which I suspect you want to do:

int (*p)[5] = new int[10][5];
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
0

Unfortunately this requires dynamic memory.

However if standard containers can be used C++11 provides the array container:

vector<array<int, 5>> foo;

Which provides 4 primary benefits over dynamic memory:

  1. It is easy to create and zero initialize elements of foo: For example to create two size 5, zeroed second dimensions you need only do: foo.resize(2)
  2. There is never a need to delete allocated memory. As soon as foo goes out of scope it will be cleaned up. Whether by throwing an error or any natural scope exit
  3. vector can attend to reallocation and data copying as the array dynamically grows or shrinks over the course of program execution
  4. If this is a member variable using a container that properly constructs and copies itself allows you to use the default generated constructors, assignment operators, and destructor

[Live Example]

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288