0

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);
1
  • 1
    Please don't cast the return value of malloc in C - it can hide problems that you don't want hidden. C is perfectly capable of changing a void* to any other pointer implicitly. Commented Sep 23, 2012 at 21:13

2 Answers 2

5

You only need:

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

and then you can access it just like an array.

aptr[0] = 123;
Sign up to request clarification or add additional context in comments.

Comments

1

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.

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.