为什么我不能直接在C中的字符串上使用strtok,为什么我需要先复制它?

问题描述 投票:0回答:1

我不明白为什么我不能直接

strtok(argv[1], ";")

(如果

argv[1]
确实是来自终端的输入,而
argv[1]
实际上是堆上的列表,会有区别吗?)

    char *multiDecimalToBinary(char *argv[], int count) {
         int maxLen = 80 * (count + 1); // Max memory needed for result in this situation
        char *result = malloc(maxLen * sizeof(char));
        if (result == NULL) {
            return NULL;
        }
        result[0] = '\0'; // Initialize the result string


    /// why I need to copy argv[1] here?
    /// I think if run through terminal, argv might be an static val,
    /// but during the test, I pass in char *test = malloc(...)
        char *s = malloc((strlen(argv[1]) + 1) * sizeof(char));
        strcpy(s, argv[1]);
        char *type = strtok(s, ";");

    //    printf("%s\n",argv[1]);
    //    char *type = strtok(argv[1], ";");
    //    printf("here\n");
    void testMultiDecimalToBinary(void) {
        char **test = malloc(5 * sizeof(char *));

        test[1] = "{char;int;unsigned char}";
        test[2] = "7";
        test[3] = "10000000";
        test[4] = "255";
        assert(strcmp(multiDecimalToBinary(test, 2),
        "0000 0111 0000 0000 1001 1000 1001 0110 1000 0000 1111 1111") == 0);

        free(test);
    }

我认为这两种方法都应该有效,但只有一种可以

c string malloc strtok strcmp
1个回答
0
投票

strtok
修改字符串 - 字符串必须是可修改的。如果不是(例如,如果您传递字符串文字),那么您将调用未定义的行为。

即使可以修改字符串,有时您可能希望保留原始字符串。在这种情况下,您还需要进行深层字符串复制。

© www.soinside.com 2019 - 2024. All rights reserved.