0

我想将数据复制char*到另一个最后地址char*

插图

var1 -> O
var2 -> K

第一步

var1 -> OK
var2 -> K

复制var2var1

结果

var1 -> OK

书面代码

#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]

问题

为什么我的代码不起作用?或者是否已经存在任何功能来执行这些,但我还不知道?

感谢您的关注

4

3 回答 3

4

You aren't setting res[0] at any point. If res[0] contains \0 your string ends there. You are probably making things harder than they have to be; you can always use strncpy and strncat.

于 2011-05-27T08:01:28.167 回答
0
#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[0] = 0x4f;


char a[] = {0x4b};


timpah(res,a,1,0);

res[2] = '\0';
printf("%s [%d]\n",res,strlen(res));
return 0;
}
于 2011-05-27T08:13:19.400 回答
0

你可能应该看看 strncat()、strncpy() 等

于 2011-05-27T08:02:53.057 回答