简体   繁体   中英

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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM