I need to create a global array in C with user input size

Basically I need to make a global variable in C which is an array. The array will be [n] [22] [n + 1], where n is 3,4,5 or 6 and selected by the user.

Is there a way to do this, or should I just make an array [6] [22] [7] and have functions in it that use only parts up to n (if that makes sense)?

I had to do this before for the computer science class, but I can’t remember exactly how to do it.

+3
source share
3 answers

For an array that is small (well, assuming data types are reasonably sized), you might be better off making the selection [6][22][7] that you mentioned in your question - this is not like what you spend so much space. Unfortunately, for you, variable length arrays of C99 do not work for global arrays. This means that your only option is to dynamically allocate using malloc() / free() .

+3
source

You can use a file area pointer that points to the first element of the array that you dynamically allocate (the malloc function) in the function.

0
source

As mentioned earlier, in this particular case, doing anything other than a static assignment [6][22][7] would be a waste of time. If you really want to dynamically allocate an array using malloc :

 /* Suppose that you want a [5][22][6] */ int main() { int i,j,k; int ***boo; int d_1,d_2,d_3; d_1=5; d_2=22; d_3=6; /* +------------------------------------------+ | For each dimension, a malloc is needed | +------------------------------------------+ */ boo = malloc(d_1*sizeof(int*)); for (i=0;i<d_1;i++) { boo[i] = malloc(d_2*sizeof(int*)); for (j=0;j<d_2;j++) { boo[i][j] = malloc(d_3*sizeof(int*)); for (k=0;k<d_3;k++) { boo[i][j][k] = i+j*k; } } } /* +----------------------+ | Testing the values | +----------------------+ */ for (i=0;i<d_1;i++) { for (j=0;j<d_2;j++) { for (k=0;k<d_3;k++) { printf("%d ",boo[i][j][k]); } printf("\n"); } } return 0; } 

That would essentially do the trick. This can be useful if you have more data.

Remember to free memory with free()

0
source

Source: https://habr.com/ru/post/1201126/


All Articles