作者sighAll (sigh)
看板C_and_CPP
标题[问题] array pointer的问题
时间Sun Jul 29 17:54:53 2018
大家好 朋友问了一个题目 说哪里有错
char * saveString(const char * s)
{
// allocate memory for a copy of the input string s
char *p = (char*) malloc(strlen(s));
while (*s)
{
*p++ = *s++;
}
*p = '\0'; // null-terminate saved copy
return p;
}
小弟研究半天 後来终於找到解答 多一个char *temp 去让p指过去 最後return temp,
但我不晓得为什麽原本的写法有问题
以下是可以compiler和回传回来是正确的code
请大大开示 谢谢!!
char * saveString(char * s)
{
// allocate memory for a copy of the input string s
char *p = (char*) malloc(strlen(s));
char *temp;
temp = p;
while (*s)
{
printf("*s=%c\n", *s);
*p++ = *s++;
}
*p = '\0'; // null-terminate saved copy
return temp;
}
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 1.161.253.187
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1532858095.A.F7D.html
1F:→ leo850319: 因为你的p一直++ 07/29 18:03
2F:→ james732: strlen应该不包含\0的长度吧? 07/29 18:21
3F:推 cutekid: malloc 少 1 byte 07/29 18:30
4F:→ sighAll: malloc加一个byte也是一样结果 07/29 18:44
5F:推 jerryh001: 1楼的对 07/29 19:02
6F:推 cutekid: p 的位置已经不在字串开头,跑到结尾了 07/29 20:05
7F:→ Gway: malloc改成(strlen(s)+1) while loop 改成 while (*s != 07/29 21:42
8F:→ Gway: ‘\0’) 配合原先temp写法较佳 07/29 21:42
9F:推 Gway: 你的temp跟p 建议交换使用 语意上比较清楚 temp 用来操作指 07/29 21:44
10F:→ Gway: 标 p是new alloc要传回的指标 07/29 21:44
11F:→ sighAll: 谢谢大家 顿时豁然开朗! 07/29 21:47
12F:推 BelieveRich: 所以最後是什麽问题? 07/30 01:51
13F:推 steve1012: 他的p已经移动了 并不是指到字串的头 07/30 03:13