user2519193
user2519193

Reputation: 211

Why does my C dynamic array give me access violation?

Here is the code I have.

int *arr;  // Indented this line
int sizeOfArr = 0;

printf("Enter size of arr.\n");
scanf("%d", &sizeOfArr);

arr = malloc(sizeOfArr * sizeof(int));

for (int i = 0; i < sizeOfArr; i++) {

    scanf("%d", arr[i]);

}

For example, if the size of the dynamic array is 5, and I proceed to enter the input "1 2 3 4 5", the entire program crashes and gives me access violation.

Upvotes: 1

Views: 87

Answers (1)

asad_hussain
asad_hussain

Reputation: 2001

In order to store array elements you need to use scanf("%d", &arr[i]); instead of scanf("%d", arr[i]);

& in C is used to refer to address of a variable. So,by using &arr[i] you are telling your program to store the input variable at ith index of array arr[].

So the correct code will be

int *arr;
int sizeOfArr = 0;

printf("Enter size of arr.\n");
scanf("%d", &sizeOfArr);

arr = malloc(sizeOfArr * sizeof(int));

for (int i = 0; i < sizeOfArr; i++) {

    scanf("%d", &arr[i]); //notice the diff here

}

Upvotes: 3

Related Questions