The following code aborts with a segmentation fault error at the commented line. The line is intended to do a simple replacement of one character.
#include <stdio.h>
#include <ctype.h>
int num(char zf[], int n) {
int i;
for (i = 0; i < n; i++) {
// assignment = seg fault
if (zf[i] == ',') zf[i] = '.';
if (!isdigit(zf[i]) && zf[i] != '+' && zf[i] != '-' && zf[i] != '.') {
return 0;
}
}
return 1;
}
int main(void) {
if (num("-3+3,0", 6)) {
printf("valid\n");
} else {
printf("not valid\n");
}
return 0;
}
I'm looking for an explenation why there's an error and what the solution is to this? strncpy? The parameters and datatypes of the function num are not to be changed.