jack.math
jack.math

Reputation: 29

Allocating memory with malloc getting error

int n;
scanf("%d",&n);
int *score;
score=(int *)malloc(sizeof(int)*n);
int i;
for (i=0;i<n;i++)
{
    scanf("%d",sizeof(int)*i+score);
}
printf("ok");

In the above code I get an error but when I comment the last line printf the program runs correctly. what is the problem?? (I want to give n number from user without using arrays)

Upvotes: 0

Views: 105

Answers (2)

SoronelHaetir
SoronelHaetir

Reputation: 15182

scanf("%d",sizeof(int)*i+score);

pointer arithmetic uses the pointer type, so here you are moving to sizeof(int)isizeof(int) bytes after score, instead just use scores+i.

Upvotes: 0

Pointer arithmetic of the form score + i is already done in multiples of sizeof(*score). So when you write score + i * sizeof(int) you doubly multiply by the size of the items. You reach way beyond the bounds of the buffer.

Either write it simply as score + i, or if you insist on doing the multiplication yourself, be sure to cast to a character pointer type first:

(int*)((char*)score + i * sizeof(int))

Oh, and don't cast the result of malloc. C doesn't require it, and it's somewhat unidiomatic.

Upvotes: 2

Related Questions