简体   繁体   English

C语言的新手,不确定为什么这个简单的程序会出现段错误

[英]New to C, not sure why this simple program is segfaulting

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

int main(){
    char *p = "26/02/1992";


    char *day;
    char *month;
    char *year;

    const char *delimiters = "/";

    day = strtok(p, delimiters);
    month = strtok (NULL, delimiters);
    year = strtok (NULL, delimiters);

    printf("%s  %s  %s\n", day, month, year);

    return 0;
}

Hey, I am just starting with C and trying out some things. 嘿,我只是从C开始,然后尝试一些东西。 Part of a program I am trying to create involves having to delimit strings. 我尝试创建的程序的一部分涉及到必须分隔字符串。 The above code is me trying to figure out how to do that. 上面的代码是我试图弄清楚该怎么做。 But, I keep getting segmentation faults when trying to run this but I have no idea why. 但是,尝试运行此方法时,我总是遇到分段错误,但我不知道为什么。 I assume it is because I have done something wrong with pointers here, any help would be great 我认为这是因为我在这里对指针做错了,任何帮助都会很棒

Is it related to the way I have defined the day, month, year pointers? 它与我定义日,月,年指针的方式有关吗?

strtok modifies the string as it parses it. strtok在解析字符串时会对其进行修改。

But you created a constant, literal string with "26/02/1992" , so it cannot be modified. 但是您使用"26/02/1992"创建了一个常量文字字符串,因此无法对其进行修改。
(it is a read-only piece of data built into your program). (这是程序中内置的只读数据)。

To stop the seg-fault, you'll want to make a copy of the string in memory, where you are allowed to modify it. 要停止seg-fault,您需要在内存中复制字符串,并可以在其中进行修改。 strdup (String Duplicate) is a good function for this, but you'll need to free the memory when you're done with it. strdup (字符串重复)是一个很好的功能,但是完成后需要free内存。

char *p = strdup("26/02/1992");  // Make a copy of the literal string, but a copy you can modify.

[... do all your work  ...]

free(p);  // Free up your copy of the string.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM