user466534
user466534

Reputation:

What's wrong with my memcpy?

I have written a function to implement memcpy

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
char *memcpy(char *dest,char *src,int n){

    char *ch=dest;
    while (n--)
        *ch++=*src++;
    return  dest;
}

int main(){

    char *src="georgia";
    int n=strlen(src);
    char *dest=new char[n];
    std::cout<<*memcpy(dest,src,n)<<std::endl;
    return 0;
}

But it only prints a single g. Why?

Upvotes: 2

Views: 1409

Answers (4)

Maciej Hehl
Maciej Hehl

Reputation: 7995

Your memcpy() returns a pointer to char. In the line

std::cout<<*memcpy(dest,src,n)<<std::endl;

you dereference the pointer (you use operator*) so effectively you send one char (the one the return value points to) to the stream.

There is a bug in your code. strlen returns number of characters in the literal "georgia", but wihtout the terminating null character. You should increase n by one, to allocate appropriate storage for dest and to copy also the terminating null character.

Upvotes: 3

zneak
zneak

Reputation: 138251

Because you're printing a single character.

std::cout<<*memcpy(dest,src,n)<<std::endl;

This dereferences the destination buffer (*memcpy) and therefore returns the first character of the string (which is g). You should be fine using this:

std::cout << memcpy(dest, src, n) << std::endl;

Other than that, it's still not gonna work: you need to include the terminating NULL character of your string in the copy, but strlen excludes it from the length of the string; so your buffer is missing 1 character. You need to add 1 to n to balance it, and everything should be fine.

int n = strlen(src) + 1;

Upvotes: 14

Pace
Pace

Reputation: 43937

Nothing wrong with the memcpy function but you have the * operation on the result. If we break the print line down it is...

char * result = memcpy(dest,src,n);
std::cout << *result << std::endl;

You really want...

std::cout << memcpy(dest,src,n) << std::endl;

Upvotes: 3

arsenm
arsenm

Reputation: 2933

You're dereferencing a char*, which is a char. This will be the first character, g.

Upvotes: 2

Related Questions