编译连接没问题,运行什么都没出现,eclipse下 gcc
#include<stdio.h>
#include<string.h>
char* comcat(char*head,char*tail)
{
char* temp_head = head;
char* temp_tail = tail;
if(head == NULL)
printf("the first string is not egist,please be check it!\n");
else
{
while(*temp_head++ != '\0'){;}
while(*temp_tail++ != '\0'){*temp_head++ = *temp_tail++ ;}
*temp_head = '\0';
}
return head;
}
int main()
{
char *a = "are you "
"ready?";
char *b = "yeah";
char *c = comcat(a,b);
printf("%s\n",c);
return 0;
} c eclipse string gcc null
[解决办法]
因为你的语法都是正确的 所以gcc可以通过,但是因为你的a分配的空间根本放不下a和b的字符数,所以当你调用的时候会内存溢出,还有你这个函数想干啥while(*temp_tail++ != '\0'){*temp_head++ = *temp_tail++ ;}每次循环指向b的指针都移动了两个字符,就算a可以放下最后只把eh连接到了a后面
[解决办法]
下次再提问,编译器里面可以格式代码的,麻烦格式化一下,否则没人原因看乱七八糟的代码
#include<stdio.h>
#include<string.h>
char* comcat(char*head,char*tail)
{
char* temp_head = head;
char* temp_tail = tail;
if(head == NULL)
printf("the first string is not egist,please be check it!\n");
else
{
while(*temp_head++ != '\0'){;}
while(*temp_tail != '\0'){ // temp_tail++ 这个就不该需要了吧
*temp_head++ = *temp_tail++ ; // 你写入的内存区域是常量区,不允许写入的,所以会报错段错误!
*temp_tail++;
}
*temp_head = '\0'; // 同理,段错误!
}
return head;
}
int main()
{
char *a = "are you ready?"; // 这是 常量指针 char*a ==> const char* a 所指向内存是不允许改变的,也就是常量区
char *b = "yeah";
char *c = comcat(a,b);
printf("%s\n",c);
return 0;
}
[解决办法]
ANSI C明确说明:修改字符串常量,效果是未定义的。