编译器不显示任何错误或警告但该程序不起作用

dim*_*ima 1 c gcc pointers compiler-errors compiler-warnings

我试图构建并运行以下程序,但它会分解执行.我想也许我犯了一个错误,但是显示了0个错误和0个警告.

在stackoverflow上研究这样的行为后,我大多看到一些错位的分号或遗忘的地址操作符,我在这个源代码中没有看到或者我忽略了什么?一些C或GCC大师可以告诉我什么是错的,为什么?

操作系统是Windows 7,编译器已启用:-pedantic -w -Wextra -Wall -ansi

这是源代码:

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

char *split(char * wort, char c)
{
    int i = 0;
    while (wort[i] != c && wort[i] != '\0') {
        ++i;
    }
    if (wort[i] == c) {
        wort[i] = '\0';
        return &wort[i+1];
    } else {
        return NULL;
    }
}


int main()
{
    char *in = "Some text here";
    char *rest;
    rest = split(in,' ');
    if (rest == NULL) {
        printf("\nString could not be devided!");
        return 1;
    }
    printf("\nErster Teil: ");
    puts(in);
    printf("\nRest: ");
    puts(rest);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

预期的行为是字符串"Some some here"在其第一个空格''拆分,预期输出为:

Erster Teil: Some

Rest: text here
Run Code Online (Sandbox Code Playgroud)

Iha*_*imi 5

您正在修改字符串文字,这是未定义的行为.改变这个

char* in = "Some text here";
Run Code Online (Sandbox Code Playgroud)

char in[] = "Some text here";
Run Code Online (Sandbox Code Playgroud)

这使得in一个数组并初始化它"Some text here".您应该使用const以防止在定义指向字符串文字的指针时意外地出现此错误.

  • 不,第一个声明指针第二个是数组.数组和字符串文字"这里有些文字"`不是同一个对象,数组是可修改的字符串文字不是.第一个定义,创建一个指向字符串文字的指针,因此当您修改它时,实际上是在修改字符串文字本身.作为函数参数,如果这就是你的意思,那么数组总是被转换为指针. (2认同)
  • 或者你可以`char array [] ="这里有些文字"; char*in = array;`. (2认同)