Page 1 of 1

Copy unsigned char* to int Variable

Posted: Wed Apr 14, 2004 6:40 am
by Fresh
Hi,

Help plz, attached is my code. Is it a right way to copy unsigned char* to int variable? Thanks in advance...

-fresh :oops:

[cpp]

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void main()
{
int len;
char tmp[1024*8];
unsigned char *ptr, buf[1024*8];
char *s1 = "ACM INTERNATIONAL COLLEGIATE PROGRAMMING CONTEST";
char *s2 = "PROBLEM SET ARCHIVE with ONLINE JUDGE";

// Assign to buffer...
ptr = buf;
memset(buf, 0, sizeof(buf));

len = strlen(s1) + 1;
memcpy(ptr, &len, sizeof(int));
ptr += sizeof(int);
memcpy(ptr, s1, len);
ptr += len;

len = strlen(s2) + 1;
memcpy(ptr, &len, sizeof(int));
ptr += sizeof(int);
memcpy(ptr, s2, len);
ptr += len;

// Read again...
ptr = buf;

memcpy(&len, ptr, sizeof(int)); // Is it a right way to copy
ptr += sizeof(int); // unsigned char* to int variable?
memcpy(tmp, ptr, len);
ptr += len;
printf("%s\n", tmp);

memcpy(&len, ptr, sizeof(int));
ptr += sizeof(int);
memcpy(tmp, ptr, len);
ptr += len;
printf("%s\n", tmp);
}

[/cpp]

Posted: Wed Apr 14, 2004 8:20 am
by Dominik Michniewski
You can do this in this way, but I think, that simplier is:

Code: Select all

len = (int)ptr; // type-cast is not necessary, but it's good practice ;-)
because any pointer is integer variable (and it's size depends of architecture of operating system! i.e. in DOS standard pointer has two bytes and 'far' pointer - four; if I don't make mistake - on Unix standard pointer has always four bytes). And you don't use any function ;-)

Best regards
DM