mwcmitchell - 5 months ago 36

C Question

I've been working on a problem for school for the past few hours and one problem I can't debug is driving me insane...

I can get to this function fine, and entering numbers into the array using scanf seems to work, but the printf statements NEVER work on the first run of the loop. Similar functions have done the same thing in past assignments. I probably have a one off somewhere but I've searched and have had no luck so I'm here with a pastebin link:

`#include <stdio.h>`

#include <stdlib.h>

#define MAXARRAYSIZE 10

static float * getGrades (int numGrades);

static float * getWeights ();

int main(void) {

float * w;

w = getWeights();

return 0;

}

float * getWeights() {

static float weights[MAXARRAYSIZE];

static float temp;

printf("Please enter up to %d numbers representing an evaluation scheme!(between 0>100)\n", MAXARRAYSIZE);

for (int i = 0; MAXARRAYSIZE > i; i++) {

scanf("%f\n", &temp);

printf("temp is: %f\n", temp);

printf("??????????");

if (100 > temp && temp > 0) {

weights[i] = temp;

printf("WEIGHTS[i] %f \n", weights[i]);

} else if (i < 1) {

exit(-1);

} else {

printf("Invalid input!");

return weights;

}

}

return 0;

}

Answer

Remove the newline from your `scanf`

call.

```
#include <stdio.h>
#include <stdlib.h>
#define MAXARRAYSIZE 50
float * getweights() {
float* weights = malloc(MAXARRAYSIZE * sizeof(float));
static float temp;
printf("Please enter up to %d numbers representing an evaluation scheme!(between 0>100)\n", MAXARRAYSIZE);
for (int i = 0; MAXARRAYSIZE > i; i++)
{
scanf("%f", &temp);
printf("temp is: %f\n", temp);
printf("??????????");
if (100 > temp && temp > 0)
{
weights[i] = temp;
printf("WEIGHTS[i] %f \n", weights[i]);
}
else if (i < 1)
{
exit(-1);
}
else
{
printf("Invalid input!");
return weights;
}
}
return weights;
}
int main() {
float *weightsp;
weightsp = getweights();
free(weightsp);
return 0;
}
$ charlie on work-laptop in ~
❯❯ ./eval
Please enter up to 50 numbers representing an evaluation scheme!(between 0>100)
10
temp is: 10.000000
??????????WEIGHTS[i] 10.000000
20
temp is: 20.000000
??????????WEIGHTS[i] 20.000000
^C
```