Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy arrray to array using memcpy() in C

Tags:

c

I am trying copy an array (temp) from another array a. But I have it is not happening.

Fig-1

int main()
{
    typedef int arr_1[3];
    arr_1 arr[4];
    arr_1 *temp;
    arr_1 a[3] = {1, 2, 3};
    memset(&temp, 0, sizeof(temp));
    memcpy(temp, a, sizeof(temp));
}

But when I tried with a simple program like below,

Fig-2

 main()
    {
    int abc[3], def[3];
    def[3] = {1, 2, 3};
    memcpy(abc, def, sizeof(abc));
    }

This above code (fig-2) worked really fine for me. But fig-1 is not working for me. Both are alomost same. But why the fig-1 is not working??

like image 703
Rasmi Ranjan Nayak Avatar asked Mar 28 '13 15:03

Rasmi Ranjan Nayak


People also ask

How does memcpy work in C?

In the C Programming Language, the memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. It returns a pointer to the destination. The memcpy function may not work if the objects overlap.

Does memcpy copy the address?

The memcpy function is used to copy a block of data from a source address to a destination address.


2 Answers

Because temp is not an array, it's a pointer and therefore sizeof(temp) has absolutely no relation to the array.

You want to change the memcpy to use sizeof(a). You will also want to give temp a sane value before copying to it, otherwise the program has undefined behavior.

like image 146
Jon Avatar answered Sep 27 '22 19:09

Jon


You must allocate memory for temp with malloc() for example. For now it`s just an uninitialized pointer.

like image 42
Johnny Mnemonic Avatar answered Sep 27 '22 20:09

Johnny Mnemonic