1

I'm studying the preprocessors and got stuck with arrays. I use below preprocessor to initialise an array containing pre defined values.

#ifndef ARRAY
#define ARRAY
    const char arr[]={10,20,30,40,50,60,80};
#endif

But their comes a problem. I want to take user input in that array. So, how can I write an array of dynamic size with preprocessor so that I can also take user input in it.

I've tried this but it gives me an error.

#define n 0

#ifndef ARRAY
#define ARRAY
    const char arr[n] {};
#endif
  • 3
    Preprocessor is compile time, user input is runtime. You cannot design something static that relies on information you get at runtime – Psi Jul 20 '19 at 16:17
  • But i just want to initialize array in preprocessor, and then the array will take user input during runtime (like function declaration). Is it not possible? – Lokesh Sharma Jul 20 '19 at 16:26
  • What does the preprocessor have to do with any of this? – melpomene Jul 20 '19 at 16:28
  • Not without dynamic memory allocation. static arrays arep placed on the stack, allocated memory on the heap. You can't dynamically initialize stuff on the stack. For stack allocation, the entire size of what needs to be placed there has to be known at compile time. – Psi Jul 20 '19 at 16:28
  • Maybe right, but still, compile time allocation with a variable as the size is not supported, at least in C. In C#, it is. – Psi Jul 20 '19 at 16:30
  • @Psi If you're talking about `int n = get_user_input(); char arr[n];`, that absolutely is supported. – melpomene Jul 20 '19 at 16:31
  • Thanks for the clarification. Maybe C99 got rid of more limitations than I expected. – Psi Jul 20 '19 at 16:33
  • You can use malloc function for dynamic memory allocation. – Roman Kwaśniewski Jul 20 '19 at 16:33
  • thanks @Psi , i got it now. – Lokesh Sharma Jul 20 '19 at 16:33

1 Answers1

0

Preprocessor is going to happen once, before compiling, so you will have to figure out the maximum size of the array beforehand, in order to set a fix size, like this.

Otherwise, you will have to use the heap (malloc or realloc) or VLAs to create an array whose size depends on the user(in your particular case) at runtime.

Jose
  • 3,004
  • 1
  • 14
  • 22