c - 使用strtok在c中分割一个字符串

标签 c undefined-behavior c-strings strtok string-literals

在下面的代码中,我尝试拆分一个字符串以从字符串中获取用“,”分隔的名称。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(void)
{
    char *st = "Addison,Jayden,Sofia,Michael,Andrew,Lily,Benjamin";
    char *name[7];
    char *separate = ",";

    char *token = strtok(st, separate);
    int i = 0;
    while(token != NULL)
    {
        strcpy(name[i], token);
        token = strtok(NULL, ",");
        i++;
    }
    for (int j = 0; j < 7; j++)
    {
        printf("%s\n", name[j]);
    }
}

但是,当我尝试运行代码时遇到了段错误。我尝试调试它,似乎这行特定的代码是错误的来源:

char *token = strtok(st, separate);

谁能告诉我我做错了什么?

最佳答案

你声明了一个指向字符串文字的指针

char *st = "Addison,Jayden,Sofia,Michael,Andrew,Lily,Benjamin";

您不能更改字符串文字。任何更改字符串文字的尝试都会导致未定义的行为。

来自 C 标准(6.4.5 字符串文字)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined

另一方面,标准 C 函数 strtok 更改传递给它的字符串。

来自C标准(7.23.5.8 strtok函数)

4 The strtok function then searches from there for a character that is contained in the current separator string. If no such character is found, the current token extends to the end of the string pointed to by s1, and subsequent searches for a token will return a null pointer. If such a character is found, it is overwritten by a null character, which terminates the current token. The strtok function saves a pointer to the following character, from which the next search for a token will start.

所以用声明代替

char st[] = "Addison,Jayden,Sofia,Michael,Andrew,Lily,Benjamin";

您还声明了一个未初始化的指针数组。

char *name[7];

所以这个声明

strcpy(name[i], token);

还调用未定义的行为。

相反你可以写

name[i] = token;

并且由于变量 i 包含 tfokens 的数量,因此通常这个循环

for (int j = 0; j < 7; j++)
{
    printf("%s\n", name[j]);
}

至少应该像这样重写(不使用魔数(Magic Number) 7)

for (int j = 0; j < i; j++)
{
    puts( name[j] );
}

关于c - 使用strtok在c中分割一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63940906/

相关文章:

python - 使用 ctypes 在 Python 中访问 c​​_char_p_Array_256

c - 尽管有用户输入,为什么我的变量被分配为 0?

MySQL 使用 "-"作为不同

C++ strlen() 初始化的char数组

c++ - 定义放置 C 字符串的位置

c++ - 我怎样才能得到一串我的语言环境的空格?

c++ - 一些内存似乎在 malloc() 和 free() 之后分配

c - 我试图终止使用 fgets() 函数的 while() 循环

c - 使用 select 进行套接字编程

c - 使用 UB 打印的宏功能