0

I need help with creating a 1-dimensional array using the length that the user entered it. I need to use a scanf_s as this is part of the assignment. I know this is something to do with pointers but I'm still new and unfamiliar on how to use them. Thanks for the help!

int main(void)
{
    unsigned int N;
    printf("%s", "Please enter a positive integer: ");
    scanf_s("%d", &N);

    int array[N];
}

I'm getting an error at int array[N];

Kareem
  • 1
  • 2
  • 3
    If this is Microsoft compiler, it does not support VLA (variable length array) and you must dynamically allocate the memory with a function such as `malloc()`. That is where your pointer will be obtained. – Weather Vane Nov 06 '21 at 20:03
  • 2
    "*I'm getting an error*". Please edit the question to show the exact error. You may also consider searching for that error on Stack Overflow or in your favourite search engine. – kaylum Nov 06 '21 at 20:05
  • I'm sorry I forgot to clarify. Yes, I am using Microsoft Visual Studio – Kareem Nov 06 '21 at 20:14

1 Answers1

0

You are trying to create a static array with a malleable value. This will not work on certain compilers. I recommend using malloc():

int main(void)
{
    unsigned int N;
    printf("%s", "Please enter a positive integer: ");
    scanf_s("%d", &N);

    int* array = (int *)malloc(N * sizeof(int));
    /* Your code */
    free(array);
}

One catch about malloc() is that you need to call free() to give the memory you allocated, back to the system. Therefore, I added a comment (/* Your code */) to indicate where the code using array should go, and added free(array); to free the memory that was allocated.

PQCraft
  • 328
  • 1
  • 8
  • 1
    Hmm... Weird I am getting an error underneath `malloc`. It says: a value of type "void" cannot be used to initialize an entity of type "int *" – Kareem Nov 06 '21 at 20:13
  • @MrGriefer I updated my answer, try adding `(int *)` before the malloc. Malloc returns a type of `void*` so casting it to `int*` should work. – PQCraft Nov 06 '21 at 20:17
  • 2
    @MrGriefer Note that the cast from `void *` is ***not*** required in standard-conforming C. Make sure you're not compiling as C++ instead of C. See [**Do I cast the result of malloc?**](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Andrew Henle Nov 06 '21 at 20:28
  • MrGriefer, PQCraft, In C, Better as `int* array = malloc(sizeof *array * N);` – chux - Reinstate Monica Nov 07 '21 at 01:35