开发者

CANNOT copying char into last address of char* ( string )?

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


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.


You probably should have a look at strncat(), strncpy(), etc


#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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜