fenigo69 fenigo69 - 4 days ago 5
C Question

Error in array allocation in C

i've try to compile this simple program, it will alloc a dyamic array and return it with a multiple of 5 in every location. but it doesn't work, it report me an error in the pointer.

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

int main(int argc, char const *argv[]) {
int n;
int i;
int* ptra;
scanf("%d",&n);
ptra=malloc(n*(sizeof(int)));

for(i=0;i<=n;i++){
ptra[i]=(5*(i+1));
printf("%d\n",ptra[i]);
}
return 0;
}

usr usr
Answer

Index range for ptra must be from 0 to n-1 (both inclusive). But here:

for(i=0;i<=n;i++){

you are going out of bounds, which is undefined. Change it to:

for(i = 0; i < n; i++) {

Note: Always check the return of all the standard functions for failures (scanf() and malloc() in your code).

Comments