strtol重用param

时间:2012-12-19 11:59:09

标签: c pointers strtol

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

#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(源)和&amp; p作为参数2(第一个无效字符的地址)是有效的吗?

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

是的,这是有效的,因为你将指针保持在字符串的开头(指针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指针,你总是可以释放占用的内存。

答案 2 :(得分:1)

是的,这是安全的。

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