0

I want the length of this array to be taken as input from user. let n be the entered length; when I use malloc: int *arr1[n] = malloc((sizeof(int) * n) + 1); it says a variable sized array can't be initialized, is there any other way to do it?

I want to take an array as input from the user, sort the elements of the array and store the sorted elements in another array. Here's my complete code:

#include <stdio.h>
#include <stdlib.h>

void swap(int *a, int *b)
{    
    int temp = 0;
    temp = *a;
    *a = *b;
    *b = temp;
}

int main(void)
{    
    int n = 0;
    printf("Enter the number of elements - ");
    scanf("%i", &n);
    int *arr1[n];
    int arr2[] = malloc((sizeof(int) * n) + 1);
    printf("Enter the elements one by one - ");
    for (int i = 0; i < n; i++)
    {
        scanf("%i", arr1[i]);
    }
    free(arr2);
}

I didn't declare the second array as arr2[n] as n is variable and it won't let me initialize the array with malloc. Can someone please help me with this?

4
  • int arr1[n] = malloc((sizeof(int) * n) + 1), why you make it as areay malloc just return generic pointer (pointer to void) location first address in the reserved block so just make it int *= (int)malloc((sizeof(int) * n) + 1); now you have an array !. Commented Apr 12, 2020 at 8:39
  • 1
    Why the + 1 ? And what is arr2 for? You don't use it at all? Commented Apr 12, 2020 at 8:40
  • 1
    make sure you're aware of the difference between %i and %d in scanf Commented Apr 12, 2020 at 8:56
  • This question has already been asked here: stackoverflow.com/questions/6634888/… Commented Apr 12, 2020 at 13:39

1 Answer 1

0

There is no other way to do it, but there is a correct way:

You want this:

int arr1[n];
int *arr2 = malloc((sizeof(int) * n) + 1);
...
scanf("%i", &arr1[i]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.