我正在做strcat函数的指针版本,这是我的代码:
void strcat(char *s, char *t);
int main(void) {
char *s = "Hello ";
char *t = "world\n";
strcat(s, t);
return 0;
}
void strcat(char *s, char *t) {
while (*s)
s++;
while ((*s++ = *t++))
;
}
Run Code Online (Sandbox Code Playgroud)
这看起来很简单,但在我的Mac OS 10.10.3上运行时会出现总线错误.我看不出为什么......
在你的代码中
char *s = "Hello ";
Run Code Online (Sandbox Code Playgroud)
s指向驻留在只读内存位置的字符串文字.所以,问题是双重的
您应该使用一个具有足够长度的数组(位于读写内存中)来保存生成的(最终)字符串(没有内存溢出).
建议:不要对用户定义的函数使用与库函数相同的名称.使用其他名称,例如my_strcat().
伪代码:
#define MAXVAL 512
char s[MAXVAL] = "Hello";
char *t = "world\n"; //are you sure you want the \n at the end?
Run Code Online (Sandbox Code Playgroud)
然后
my_strcat(s, t);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
268 次 |
| 最近记录: |