Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

c - 通过放入0(segfault)来分割c字符串(splitting c-string by putting 0's (segfault) [duplicate])

A very simple C program: I want to put 0's at some points in a string to obtain sub-strings.

(一个非常简单的C程序:我想在字符串中的某些位置输入0,以获得子字符串。)

But at the first try I get segmentation fault on execution:

(但是在第一次尝试时,我在执行时遇到了段错误:)

#include<stdio.h>
#include<string.h>
int main() {
        char *a = "eens kijken of we deze string kunnen splitten";
        a[4] = ''; // this causes the segfault
        char *b = a[5]; // sort of guessed this can't work...
        printf("%s", a);
}

So the main question: why the segfault at a[4] = '\0';

(所以主要的问题是:为什么在a[4] = '\0';)

Second I'd like to split this string with the least amount of code, based on string-index...

(其次,我想根据字符串索引,用最少的代码拆分该字符串。)

  ask by Niels translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are trying to change a string literal.

(您正在尝试更改字符串文字。)

char *a = "eens kijken of we deze string kunnen splitten";

String literals are immutable in C. Any attempt to change a string literal results in undefined behavior.

(字符串文字在C中是不可变的。任何更改字符串文字的尝试都会导致未定义的行为。)

From the C Standard (6.4.5 String literals)

(根据C标准(6.4.5字符串文字))

7 It is unspeci?ed whether these arrays are distinct provided their elements have the appropriate values.

(7如果这些数组的元素具有适当的值,则不确定这些数组是否不同。)

If the program attempts to modify such an array, the behavior is unde?ned.

(如果程序尝试修改这样的数组,则行为未定义。)

Instead declare a character array

(而是声明一个字符数组)

char a[] = "eens kijken of we deze string kunnen splitten";

Also in this declaration

(同样在此声明中)

char *b = a[5];

there is a typo.

(有一个错字。)

Should be

(应该)

char *b = &a[5];

or

(要么)

char *b = a + 5;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...