此代码似乎按预期工作,使用单个指针填充数字数组
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
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;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:
在strtol中使用p作为param1(source)和&p作为param 2(第一个无效字符的地址)是有效的吗?
是的,它很安全。
完整的使用参考请参考http://en.cppreference.com/w/cpp/string/byte/strtol 。该示例的第 11 行说明了对第一个和第二个参数使用相同变量的调用。