Church
Church

Reputation: 115

Dynamically allocate an array of specified size in C

I need to create an array that's size is determined by user input, and then has pointers to said array. All the array will hold is random numbers between 500-600. I can't seem to use malloc correctly. I am still new to C, so help is appreciated.

int main(){
        int size;
    printf("Enter size of array");
    scanf("%d", &size);


    int array[size];
    int *aPtr = (int *) malloc(sizeof(int) * array);

Upvotes: 0

Views: 183

Answers (2)

petersohn
petersohn

Reputation: 11720

You probably wanted to write:

int *aPtr = (int *) malloc(sizeof(int) * size);

You don't need that array variable anyway. You can index aPtr like aPtr[10]. Also don't forget free(aPtr) at the end.

Upvotes: 1

Inisheer
Inisheer

Reputation: 20794

You only need:

int *aptr = malloc(sizeof(int) * size);

and then you can access it just like an array.

aptr[0] = 123;

Upvotes: 5

Related Questions