Segementation故障(核心转储)中的strtok [英] Segementation fault( core dumped ) in strtok

查看:225
本文介绍了Segementation故障(核心转储)中的strtok的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  内存分配的char *和char []

为什么下面的程序给出在运行时分段故障?

Why does the following program give a Segmentation fault in run-time ?

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

main()
{
    char * str = "Have a. nice, day :)";
    char * ptr;

    ptr = strtok( str, " .,");

    printf("%s",ptr);
 }

但是,如果使用的char海峡[] =有一个很好的,一天:)。它给我的输出。这是为什么我得到即使strtok的定义是错误的char *的strcpy(字符*,为const char *)???〜

But if I use char str[] = "Have a. nice, day :)"; it gives me the output. Why is that i get the error even though strtok definition is char* strcpy( char * , const char * ) ???~

推荐答案

strtok的修改参数, STR 点一个字符串,修改字符串文字的原因未定义的行为。初始化非const 的char * 用于字符串是pcated其实德$ P $。

strtok modifies the argument, str points to a string literal, modifying a string literal causes undefined behavior. Initializing a non-const char* with a string literal is in fact deprecated.

当你写海峡[] STR 变得与字符串初始化一个可变的数组。

When you write str[], str becomes a mutable array initialized with the string.

这篇关于Segementation故障(核心转储)中的strtok的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆