0

I have a C program which declares an array as such :

static unsigned char m_data[90000];

Now the program takes a file name as a command line input as follow :

./output [Filename]

I want to make this program to change the array size to the size of the file at runtime to obtain something like :

static unsigned char m_data[FILE_SIZE];

How do I do it to change the size of the array dynamically at each runtime ?

  • 1
    Read [the `stat` manual page](https://man7.org/linux/man-pages/man2/stat.2.html). – Some programmer dude Jan 22 '21 at 18:18
  • *"How do I do it to change the size of the array dynamically"* - You don't – klutt Jan 22 '21 at 18:35
  • You might want to have a look at *dynamic allocation* with `malloc` but then you have to switch the arrays for pointers. – klutt Jan 22 '21 at 18:36
  • Can you elaborate on that a bit more ? I read that but couldn't really get my head around it. [Sorry still a beginner] – WhoKilledDB Jan 22 '21 at 18:43
  • @WhoKilledDB Chapter 13.1 https://gforge.inria.fr/frs/download.php/latestfile/5298/ModernC.pdf – klutt Jan 22 '21 at 18:49
  • @klutt I cant actually switch to malloc because it's part of a huge code and then I have to re-write all of it :) – WhoKilledDB Jan 22 '21 at 18:55
  • 1
    @WhoKilledDB Well, in that case there's to little information in the question to give a proper answer. You can never change the size of an array. You can use a VLA, but those cannot be global nor static. – klutt Jan 22 '21 at 19:00
  • @WhoKilledDB I wrote a pretty extensive answer about VLA:s. You might want to have a look. https://stackoverflow.com/a/58163652/6699433 – klutt Jan 22 '21 at 19:14
  • @WhoKilledDB That's part of learning. Are you sure it'll be that bad? It may be that after making it an `unsigned char*` assigned via malloc, the only thing you need to change is any reference to `sizeof(m_data)` which you can search&replace with some variable `file_size`. – that other guy Jan 22 '21 at 19:32

0 Answers0