I am struggling with the pointer exercises for my C programming course. I am asked to calculate the arithmetic mean from comma separated list of integers using the prototype float mean(char *list);
and strtok
function. However, I can not get my function to work properly. Here is my proposed solution;
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
#include <stdio.h>
float mean(char *list);
float mean(char *list) {
const char sep[] = ",";
char *token;
token = strtok(list, sep);
int8_t value = atoi(token);
int8_t total = value;
int8_t count = 1;
while(token != NULL) {
token = strtok(NULL, sep);
value = atoi(token);
total = total value;
count = count 1;
}
double mean;
mean = total/count;
return mean;
}
CodePudding user response:
In your while loop, you are updating the token at the start of the loop, so in the next line you should check if the token has become NULL or not - but you are not checking that. Here is the code:
float mean(char *list) {
const char sep[] = ",";
char *token;
token = strtok(list, sep);
int8_t value = atoi(token);
int8_t total = value;
int8_t count = 1;
while(token != NULL) {
token = strtok(NULL, sep);
if (token == NULL) break;
value = atoi(token);
total = total value;
count = count 1;
}
double mean;
mean = total/count;
return mean;
}