0
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)

Barmar
  • 741,623
  • 53
  • 500
  • 612
jack.math
  • 29
  • 7

2 Answers2

2

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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
0
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.

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23