无法将 char 复制到 char* (字符串)的最后一个地址?
我想将char*
的数据复制到char*
的另一个最后地址
插图
var1 -> O
var2 -> K
第一步
var1 -> OK
var2 -> K
复制var2
到 var1
结果
var1 ->好的
编写的代码
#include <stdio.h>
#include <string.h>
void timpah(char *dest, char *src, int l_dest, int l_src)
{
int i = 0;
while(i < l_dest)
{
dest[l_dest+i] = src[l_src+i];
i++;
}
}
int main()
{
char res[2024];
res[1] = 0x4f;
char a[] = {0x4b};
timpah(res,a,1,1);
printf("%s [%d]\n",res,strlen(res));
return 0;
}
运行
root@xxx:/tmp# gcc -o a a.c
root@xxx:/tmp# ./a
[0]
问题
为什么我的代码不起作用?或者是否已经存在任何函数可以执行这些操作,但我还不知道?
感谢您的关注
i would like to copy data of char*
to another last address of char*
illustration
var1 -> O
var2 -> K
first step
var1 -> OK
var2 -> K
copy var2
to var1
result
var1 -> OK
written code
#include <stdio.h>
#include <string.h>
void timpah(char *dest, char *src, int l_dest, int l_src)
{
int i = 0;
while(i < l_dest)
{
dest[l_dest+i] = src[l_src+i];
i++;
}
}
int main()
{
char res[2024];
res[1] = 0x4f;
char a[] = {0x4b};
timpah(res,a,1,1);
printf("%s [%d]\n",res,strlen(res));
return 0;
}
run
root@xxx:/tmp# gcc -o a a.c
root@xxx:/tmp# ./a
[0]
question
why my code is not working ? or is there any function had exists already to perform these, but i haven't know it yet ?
thx for any attention
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在任何时候都没有设置
res[0]
。如果res[0]
包含\0
你的字符串就在那里结束。你可能让事情变得比原本应该的更加困难;您始终可以使用strncpy
和strncat
。You aren't setting
res[0]
at any point. Ifres[0]
contains\0
your string ends there. You are probably making things harder than they have to be; you can always usestrncpy
andstrncat
.您可能应该看看 strncat()、strncpy() 等
You probably should have a look at strncat(), strncpy(), etc