这段代码看起来像预期的那样工作,使用单个指针填充数字数组
#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;
}我的问题是:
在strtol中使用p作为param1 (源)并使用&p作为参数2(第一个无效字符的地址)是有效的。
发布于 2012-12-19 20:10:37
是的,它是安全的。
请参考http://en.cppreference.com/w/cpp/string/byte/strtol了解完整的使用参考。示例的第11行说明了对第一个和第二个参数使用相同的变量的调用。
发布于 2012-12-19 20:16:28
是的,它是安全的。第一个参数是通过值传递的,因此strtol有一个本地副本,该副本不受写入第二个参数的更改的影响。
发布于 2012-12-19 20:06:09
是的,这是有效的,因为您将指针保持在字符串的开头(指针s)。假设您有这样的情况:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
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指针,因此您将始终能够释放占用的内存。
https://stackoverflow.com/questions/13952015
复制相似问题