c - 为什么这会打印字符串的错误部分?
问题描述
void buggy_substring(char *input, size_t pos, size_t len)
{
input += pos;
input[len] = '\0';
}
int main(int argc, char *argv[])
{
char name[16];
strcpy(name, "Tessier-Lavigne");
buggy_substring(name, 3, 2);
printf("%s\n", name);
return 0;
}
为什么这会打印“Tessi”而不是“si”?这是将 size_t 与 char 混合的问题吗?
解决方案
您只能在函数中更改起始位置。但是,在打印时,您仍然将字符串的原始头部传递给 printf。
尝试将 name+3 传递给 printf 。
int main(int argc, char *argv[])
{
char name[16];
// allocated a buffer of 16 bytes on the stack (called name)
// note that an array of chars and a pointer to a char is NOT the same thing
strcpy(name, "Tessier-Lavigne");
// copies from a const null-terminated string
// now char* name contains
// ['T','e','s','s','i','e','r','-','L','a','v','i','g','n','e','\0']
buggy_substring(name, 3, 2);
// name is passed as an immutable number "by value",
// the value of name is not changed
// however, the contents name points to can be
// now name is
// ['T','e','s','s','\0','e','r','-','L','a','v','i','g','n','e','\0']
printf("%s\n", name);
//output 'T','e','s','s' + new line
return 0;
}
void buggy_substring(char *input, size_t pos, size_t len)
{
//local pointer input
// points to ['T','e','s','s','i','e','r','-','L','a','v','i','g','n','e','\0']
//pos=3
//len=2
input += pos;
// input points to 's' (original name still points to 'T'
input[len] = '\0';
//equivalent code
char * p=input;
p+=len;
*p='\0';
// input+2 points to 'i'
// 'i' is replaced with zero
// the original buffer looks like
//['T','e','s','s','\0','e','r','-','L','a','v','i','g','n','e','\0']
}
免责声明:当然,您应该将库字符串操作函数用于更严重的代码,并且不要尝试重新发明轮子。
推荐阅读
- cordova - 如何将cordova与内部项目localhost连接起来?
- teradata-sql-assistant - 如何修复 teradata 中没有更多的假脱机空间?
- rust - 来自原始 fd 的 BufReader
- amazon-web-services - 如何将 Docker 映像从 docker hub 部署到 AWS docker swarm 集群
- svg - Snap.svg 嵌入 html 表单
- python - 用pytest编写测试用例进行数据验证,测试用例的性质随组执行而变化
- angular - 角度传递方法到指令
- sql - 将 SELECT 数据从一个表复制到另一个表
- scala - 如何修复sparkstreaming中的任务不可序列化异常
- angular - 向服务器发送一些数据后如何重新加载组件?