strtol重用param

此代码似乎按预期工作,使用单个指针填充数字数组

#include  #include  #include  int main(void) { int arr[4], count = 0, i; char *p, s[32] = " \t 10, 15 \n ,20, 25 , "; p = s; do { arr[count++] = (int)strtol(p, &p, 10); while (isspace(*p) || *p == ',') p++; } while (*p); for (i = 0; i < count; i++) { printf("%d\n", arr[i]); } return 0; } 

我的问题是:

在strtol中使用p作为param1(source)和&p作为param 2(第一个无效字符的地址)是有效的吗?

是的,这是安全的。

有关完整的使用参考,请参阅http://en.cppreference.com/w/cpp/string/byte/strtol 。 该示例的第11行说明了对第1和第2参数使用相同变量的调用。

是的,这是安全的。 第一个参数是按值传递的,因此strtol有一个本地副本,不受写入第二个参数的更改的影响。

是的,这是有效的,因为你将指针保持在字符串的开头(指针s)。 考虑到你有这种情况:

 #include  #include  #include  #include  int main(void) { int arr[4], count = 0, i; char *p, *s; s = (char*)malloc(sizeof(char) * 15); strcpy(s, " \t 10, 15 \n ,20, 25 , "); p = s; do { arr[count++] = (int)strtol(p, &p, 10); while (isspace(*p) || *p == ',') p++; } while (*p); for (i = 0; i < count; i++) { printf("%d\n", arr[i]); } free(s); return 0; } 

strtol会将p指针移动到字符串中的某个位置。 如果您调用free(p) ,则会出现内存泄漏(如果没有失败)。 但是,由于你保持s指针,你将始终能够释放占用的内存。