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)
您正在修改字符串文字,这是未定义的行为.改变这个
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以防止在定义指向字符串文字的指针时意外地出现此错误.