problem with looping scanf
I'm trying to fix someones code for them but I've got myself stuck.
Code:
int main()
{
float x = 0, temp=0 , high, low;
int num,i,*ptr,sum = 0,mean;
char choose;
printf("This program will ask the user for a list of numbers.\n");
printf("Then calculate the median or mean average.\n\n");
printf("How many numbers are you going to put in?\n: ");
scanf("%d",&num);
ptr = (int*) malloc ( num * sizeof (int)); //Creates enough room for the array
if (ptr == NULL) printf("Malloc failed");
for (i=0;i<=num;i++) { //Fills the array with inputted values
printf("i = %d\n",i);
scanf("%d",*(ptr + i)); //PROBLEM HERE
}
After I've inputted 3 values ( I should be able to put much more in ) in crashes my dos prompt. Can anyone here see whats wrong?
This isn't full code by the way, if you are wondering why there are lots of unused variables.
Re: problem with looping scanf
Quote:
Originally posted by crag2804
I'm trying to fix someones code for them but I've got myself stuck.
Code:
int main()
{
float x = 0, temp=0 , high, low;
int num,i,*ptr,sum = 0,mean;
char choose;
printf("This program will ask the user for a list of numbers.\n");
printf("Then calculate the median or mean average.\n\n");
printf("How many numbers are you going to put in?\n: ");
scanf("%d",&num);
ptr = (int*) malloc ( num * sizeof (int)); //Creates enough room for the array
if (ptr == NULL) printf("Malloc failed");
for (i=0;i<=num;i++) { //Fills the array with inputted values
printf("i = %d\n",i);
scanf("%d",*(ptr + i)); //PROBLEM HERE
}
After I've inputted 3 values ( I should be able to put much more in ) in crashes my dos prompt. Can anyone here see whats wrong?
This isn't full code by the way, if you are wondering why there are lots of unused variables.
stuff:
you didnt return a value from main()
when you allocate space for num ints, your for loop should look like this:
for (i=0;i<num;i++)
how much do you know of pointers? i suggest getting a good book on them. scanf expects a pointer to int arg, which is why with a regular int you take the address of it with the & operator. but why are you indirecting in
scanf("%d",*(ptr + i));
? The indirection operator yields an int from a pointer to an int. but scanf expects a pointer, not an int. so you should just do
scanf("%d", ptr + i);