Copy unsigned char* to int Variable

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
Fresh
New poster
Posts: 46
Joined: Mon Apr 15, 2002 10:42 am
Contact:

Copy unsigned char* to int Variable

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

Dominik Michniewski
Guru
Posts: 834
Joined: Wed May 29, 2002 4:11 pm
Location: Wroclaw, Poland
Contact:

Post 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
If you really want to get Accepted, try to think about possible, and after that - about impossible ... and you'll get, what you want ....
Born from ashes - restarting counter of problems (800+ solved problems)

Post Reply

Return to “C++”