【问题标题】:Compiler doesn't show any errors or warnings but the program doesn't work [closed]编译器不显示任何错误或警告,但程序不工作 [关闭]
【发布时间】:2016-01-28 11:30:54
【问题描述】:

我尝试构建并运行以下程序,但它无法执行。我想也许我犯了一个错误,但显示了 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 指针。

标签: c pointers gcc compiler-errors compiler-warnings


【解决方案1】:

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

char* in = "Some text here";

char in[] = "Some text here";

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

【讨论】:

  • 好的,但是声明 "char * in" 和 "char in[ ]" 在 C 中不是等价的,那么为什么一个炒锅,另一个不炒锅?
  • 不,第一个声明一个指针,第二个声明一个数组。数组和字符串文字"Some text here" 不是同一个对象,数组是可修改的字符串文字不是。第一个定义是指向字符串文字的指针,因此当您修改它时,您实际上是在修改字符串文字本身。作为一个函数参数,如果这就是你的意思,数组总是被转换为一个指针。
  • 您需要复制字符串文字,包括 string.h 并尝试 char *in = strdup("Some text here"); if (in == NULL) return -1; /* Do whatever you can with in */ free(in);
  • 或者你可以char array[] = "Some text here"; char *in = array;
  • @dima:了解undefined behavior。使用gcc -Wall -Wextra -g 编译。 使用调试器 (gdb) & valgrind
猜你喜欢
  • 2016-02-14
  • 2021-07-27
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
  • 1970-01-01
  • 2023-03-17
相关资源
最近更新 更多