memory...bytes.....c....but?

Programming, for all ages and all languages.
Post Reply
datajack

memory...bytes.....c....but?

Post by datajack »

how would i say...copy 4096 bytes of data from pointer dest, to pointer src? and explaination would be really nice :)
AR

Re:memory...bytes.....c....but?

Post by AR »

That is an extremely basic operation, just set the contents of destination pointer to the contents of the source pointer, incrementing both as you go, ie.

Code: Select all

for(size_t i = 0 ; i < NUMBYTES ; ++i)
     destination[i] = source[i];
Or the more optimized version:

Code: Select all

__asm__ ("rep\n\t"
         "movsb\n\t" : : "eDi"(destination), "eSi"(source), "ecx"(NumBytes));
datajack

Re:memory...bytes.....c....but?

Post by datajack »

shouldent it be *dest = *src?

and, is size_t important or can it be int i?
durand
Member
Member
Posts: 193
Joined: Wed Dec 21, 2005 12:00 am
Location: South Africa
Contact:

Re:memory...bytes.....c....but?

Post by durand »

size_t is defined as an unsigned int.

Code: Select all

typdef unsigned int size_t;

void* memcpy( char *dest, const char *src, size_t n )
{ 
  size_t i;

  for ( i = 0; i < n; i++ )
    dest[i] = src[i];

  return dest;
}

It won't be *dest because the is already indexing into the array at dest.

Try and find some tutorials on pointers. It will save you a lot of headaches.

Code: Select all

int a = 5;         // a is now == 5
int *b = &a;     // b is now pointing to a
int **d = &b;   // d is now a pointer to a pointer. *d == b and **d == a.


printf("%i %i %i", a, *b, **d );  // prints three 5's.

a = 2;  // everything points to a, so this will change the output for everything.

printf("%i %i %i", a, *b, **d );  // prints three 2's.

printf("%p", b );  // prints b which is a pointer to a. 

// So, it's printing the memory location of a.

printf("%p", d );  // prints d which is a pointer to b. 

// So, it's printing the memory location of b.

printf("%p", *d );  // prints *d which is the value of b which is a pointer to a. 

// So, it's printing the memory location of a.

Joel (not logged in)

Re:memory...bytes.....c....but?

Post by Joel (not logged in) »

shouldent it be *dest = *src?

and, is size_t important or can it be int i?


size_t is whatever the appropriate data type for storing a size on the current platform is. In general, it's probably better to use size_t and not go around it by using what it's typedef'd as.

As for the memory copying, unless you're implementing the C standard library or doing a programming assignment, the standard library function memcpy already does this for you, and (unless you have a useless compiler vendor) it's probably faster than anything you would implement by hand.
AR

Re:memory...bytes.....c....but?

Post by AR »

He created this after being told that the question was more C-like then OS Dev-like, so... he's implementing the C library.
Post Reply