详细说明 Joachim Pileborg 的答案pal
是一个指向角色的指针。*pal
是 a char
,它是一个整数值,表示 pal 指向的字符。char,是最小的可寻址整数类型。
如果您要使用 strtol,最好将您更改coords
为long
,以便类型匹配。好处是 strtok 在这种解析方面非常糟糕,你可以完全放弃它。
typedef struct {
long x;
long y;
} Coord;
/* returns the number of coordinates read. */
size_t read_coordinates(char *str, Coord destination[], size_t capacity);
int main(void) {
#define EXERCISE_CAPACITY 1000
Coord exercise[EXERCISE_CAPACITY];
size_t count = read_coordinates("1 2 3 4 5 6", exercise, EXERCISE_CAPACITY);
}
size_t read_coordinates(char *str, Coord destination[], size_t capacity) {
size_t x;
for (x = 0; x < capacity; x++) {
char *endptr = NULL;
destination[x].x=strtol(str, &endptr, 10);
if (endptr - str == 0) {
// Stop when strtol says it can't process any more...
break;
}
str = endptr + 1;
destination[x].y=strtol(str, &endptr, 10);
if (endptr - str == 0) { break; }
str = endptr + 1;
}
return x;
}
如果你必须使用int
作为你的坐标类型,使用 sscanf 是明智的,有点像这样:
typedef struct {
int x;
int y;
} Coord;
/* returns the number of coordinates read. */
size_t read_coordinates(char *str, Coord destination[], size_t capacity);
int main(void) {
#define EXERCISE_CAPACITY 1000
Coord exercise[EXERCISE_CAPACITY];
size_t count = read_coordinates("1 2 3 4 5 6", exercise, EXERCISE_CAPACITY);
}
size_t read_coordinates(char *str, Coord destination[], size_t capacity) {
size_t x;
for (x = 0; x < capacity; x++) {
int n;
if (sscanf(str, "%d %d%n", &destination[x].x, &destination[x].y, &n) != 2) {
// Stop when sscanf says it can't process any more...
break;
}
str += n;
}
return x;
}