Closed. This question needs debugging details。它当前不接受答案。












想改善这个问题吗?更新问题,以便将其作为on-topic用于堆栈溢出。

4年前关闭。



Improve this question




我试图构建并运行以下程序,但执行失败。我以为也许我犯了一个错误,但显示了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;
}

预期的行为是字符串“Some text here”在其第一个空格“”处分割,预期的输出为:
Erster Teil: Some

Rest: text here

最佳答案

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

char* in = "Some text here";


char in[] = "Some text here";

这使in成为一个数组,并使用"Some text here"对其进行初始化。在定义指向字符串文字的指针时,应使用const防止意外出现此错误。

关于c - 编译器没有显示任何错误或警告,但该程序无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35060341/

10-11 22:10
查看更多