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)

4
  • scanf("%d",sizeof(int)*i+score);-->scanf("%d",&score[i]); and score=(int *)malloc(sizeof(int)*n);-->score=malloc(sizeof(int)*n); Commented Dec 25, 2017 at 7:41
  • then do this scanf("%d",score+i); Commented Dec 25, 2017 at 7:43
  • of scanf("%d", &score[i]);. And check return value of scanf. Commented Dec 25, 2017 at 7:50
  • @M.M.: That's what was being mentioned and then OP commented a requirement I shouldn't use [ or ] Commented Dec 25, 2017 at 8:00

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.