How to use struct member variable to preset matrix size

Asked

Viewed 31 times

0

I wonder how to pre define the size of an array within a shape struct:

struct exemplo{
  int l;
  int c;
  int matriz[l][c];
};

compiler claims that l and c on the matrix line is not declared here.

  • 3

    Only with the use of dynamic memory int **matriz

  • Just as @Fábiomoral indicated, the way it is written only dynamically, but if so l as c are constant, through a #define for example will already work.

1 answer

0

When working with vector, one has to bear in mind that there are two types: static vectors and dynamic vectors. The vector of your struct in this case is a static vector, you can even declare it and use it (if your code and logic are correct, of course), but the size of this vector must be declared by you, the programmer. And how to do that? With #define pre-processing commands:

#define j 10

now, when I can use j to declare a static vector, however, the user will not interfere at any time, after all, are PREPROCESSING commands. I recommend it if that’s what you want to do.

If you want a user intervention on the size of the vector, you will need a dynamic vector:

char *vetor = (char *) malloc(100 * sizeof(char));

If you want to know more about dynamic allocation, I recommend accessing this link.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.