Both x and xPlus1 should be of type double*. They are pointers to an array of n doubles.

So when you do this:

memcpy(x, xPlus1, sizeof(x));

Since x is just a double*, that only copies sizeof(double*) bytes... which is to say, 8. What you want to do is:

memcpy(x, xPlus1, n * sizeof(*x));

because the type of *x is double, so n * sizeof(*x) will be the total bytes of memory that xPlus1 owns: n doubles.

Answer from Barry on Stack Overflow
Top answer
1 of 3
4

Both x and xPlus1 should be of type double*. They are pointers to an array of n doubles.

So when you do this:

memcpy(x, xPlus1, sizeof(x));

Since x is just a double*, that only copies sizeof(double*) bytes... which is to say, 8. What you want to do is:

memcpy(x, xPlus1, n * sizeof(*x));

because the type of *x is double, so n * sizeof(*x) will be the total bytes of memory that xPlus1 owns: n doubles.

2 of 3
3

You left out the declarations.
Adding the type,

double* x = (double*) malloc(sizeof(double)*n);

makes it clearer that x is a pointer to a double.
In this particular case, the double x points to is the first element in an array of n doubles.

Something like this:

       (------- n doubles  -----)        
      ___________________________
x ===>| | | | | | | | | | | | | |
      ---------------------------

&x would give you the address of the variable x itself. This is very different from the address that the variable x contains.
(If you have int x = 1;, &x will most likely not be 1.)

memcpy takes two pointers, one for the destination and one for the source, and the size of the memory to copy.
But sizeof(x) doesn't give you the size of the array you allocated; it gives you the size of x, which is a pointer.
(Size is measured in multiples of sizeof(char), which by definition is 1, and sizeof(double*) will be 4 (32 bits) or 8 (64 bits) on most modern machines. So you're copying 32 or 64 bits.)

The size parameter should be the same size that you passed to malloc, if you want to copy the whole thing.
The pointers should be the ones returned from malloc, since these are the memory blocks you want to copy.

So,

memcpy(x, xPlus1, sizeof(double) * n);

should work as expected.

🌐
Cplusplus
cplusplus.com › reference › cstring › memcpy
memcpy
Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.
Discussions

Is there a way to memcpy an array data to another array data with specific location.
Prefer std::copy to the dangerous C library function memcpy (memcpy will only work for simple types such as integers): #include // Put at top std::copy(&x[0], &x[2], &y[3]); If you want some more advanced behavior, i.e. fill out zeros in y by copying the next element in x you have to implement it yourself with a loop and a counter. This is what programming is about: making algorithms for doing specific tasks. Unfortunately there is no standard my_specific_program() function for your project in the standard library. More on reddit.com
🌐 r/cpp_questions
18
3
September 4, 2022
c++ - Does memcpy require pointer to array rather than first element? - Stack Overflow
In the C++ standard the meaning of memcpy is taken from C (I will quote C++23 here but I don't believe the wording has changed from earlier versions): The contents and meaning of the header are the More on stackoverflow.com
🌐 stackoverflow.com
c - memcpy and pointers - Stack Overflow
I am confuse on how to read the pointers copied in an array using memcpy. Following is what I have tried, but does not work. Basically, I have allocated block of memory in which I am copying point... More on stackoverflow.com
🌐 stackoverflow.com
June 24, 2015
arrays - Using memcpy in C++ - Stack Overflow
For fundamental types like int, the bitwise copy done by memcpy will work fine. For actual class instances, you need to use std::copy (or copy_n) so that the class's customized assignment operator will be used. ... Sign up to request clarification or add additional context in comments. ... @refp: Adding a comment was fine, but there was no need to ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 153700-about-using-memcpy-arrays.html
About using memcpy on arrays:
January 13, 2013 - memcpy() takes a void * pointer as its first argument. &xn is actually a pointer-to-pointer in this usage. When you pass an array to a function, it devolves to a pointer. IE you just pass memcpy(xn, ...) not memcpy(&xn, ...) Your compiler should be warning you about this, also.
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › c_function_memcpy.htm
C library - memcpy() function
void *memcpy(void *dest_str, const void * src_str, size_t n) ... dest_str − This parameter define a pointer to the destination array where the content is to be copied.
🌐
Scaler
scaler.com › home › topics › memcpy in c
memcpy() in C
April 14, 2024 - The memcpy function in C returns a void pointer that points to the starting address of the destination memory location in which final values are stored. Let us see a simple example for memcpy in c in which the data present in the memory location ...
🌐
Linux Hint
linuxhint.com › cpp-memcpy
How to Use the C++ Memcpy Function
May 17, 2023 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
Educative
educative.io › answers › c-copying-data-using-the-memcpy-function-in-c
C: Copying data using the memcpy() function in C
In C, the memcpy() function copies n number of characters from one block of memory to another. ... Destination: Pointer to the destination array where data will be copied.
Find elsewhere
🌐
Bytes
bytes.com › home › forum › topic
problem with memcpy and pointers/arrays confusion - again - Post.Byes
March 9, 2006 - I hope it's not too advanced :-) Best regards / Med venlig hilsen Martin Jørgensen -- --------------------------------------------------------------------------- Home of Martin Jørgensen - http://www.martinjoergensen.dk ... Re: problem with memcpy and pointers/arrays confusion - again On Sat, 11 Mar 2006 12:42:13 +0100, Martin Jørgensen <unoder.spam@sp am.jay.net> wrote: [color=blue] >#include <stdio.h> >#include <stdlib.h> > >int main() >{ > unsigned long int total_mem_used = 0; // counter > int N = 20; // whatever number of elements > > int *int_array = allocate_mem((N +1)*sizeof(int) , __FILE__, >__LINE__, &total_mem);[/color] There is no prototype in scope for allocate_mem.
🌐
cppreference.com
en.cppreference.com › cpp › string › byte › memcpy
std::memcpy - cppreference.com
#include <cstdint> #include <cstring> #include <iostream> int main() { // simple usage char source[] = "once upon a daydream...", dest[4]; std::memcpy(dest, source, sizeof dest); std::cout << "dest[4] = {"; for (int n{}; char c : dest) std::cout << (n++ ? ", " : "") << '\'' << c << "'"; std::cout << "};\n"; // reinterpreting double d = 0.1; // std::int64_t n = *reinterpret_cast<std::int64_t*>(&d); // aliasing violation std::int64_t n; std::memcpy(&n, &d, sizeof d); // OK std::cout << std::hexfloat << d << " is " << std::hex << n << " as a std::int64_t\n" << std::dec; // object creation in dest
🌐
cppreference.com
en.cppreference.com › c › string › byte › memcpy
memcpy, memcpy_s - cppreference.com
#define __STDC_WANT_LIB_EXT1__ 1 #include <stdio.h> #include <stdint.h> #include <inttypes.h> #include <string.h> #include <stdlib.h> int main(void) { // simple usage char source[] = "once upon a midnight dreary...", dest[4]; memcpy(dest, source, sizeof dest); for(size_t n = 0; n < sizeof dest; ++n) putchar(dest[n]); // setting effective type of allocated memory to be int int *p = malloc(3*sizeof(int)); // allocated memory has no effective type int arr[3] = {1,2,3}; memcpy(p,arr,3*sizeof(int)); // allocated memory now has an effective type // reinterpreting data double d = 0.1; // int64_t n =
🌐
Javatpoint
javatpoint.com › memcpy-in-c
memcpy() in C - javatpoint
If we want to create an Array, we declare the Data type and give elements into it: #include&lt;stdio.h&gt; int main() { int i, arr[5] = {1, 2, 4, 2, 4}; for(i = 0; i...
Top answer
1 of 1
4

You're right that in a pedantic reading of the standard, we would need to take the address of the array instead of passing buf because array-to-pointer conversion obtains a pointer to the first element. std::memcpy(buf, &obj, N); would therefore write past the end of the first char object in buf, which is not okay if it writes

into the object pointed to by s1

Another bit of broken wording in this area is that we never clearly specify that you can use an unsigned char*/char* to "navigate" the bytes of an object, and P1839R7 Accessing object representations deals with that problem. Currently, memcpy just "magically" copies the object even though the user couldn't implement that.

In general, the wording in these areas of both the C and C++ standard is pretty defective. However, this doesn't really matter in practice. std::memcpy(buf, &obj, N); is expected to work by users, compilers consider it to be valid, and disallowing it would break immeasurable amounts of code.

How to fix it

The C++ standard generally only specifies additional semantic on top of C functions like in [cstring.syn] p3; it doesn't fully redefine them.

Therefore, this wording would have to be fixed on the C side, and the process is explained at https://www.open-std.org/jtc1/sc22/wg14/www/contributing.html What we probably want to say is that memcpy copies bytes of storage from the source into the destination, and that this can access bytes not just from a single object but also from the surrounding array, if any.

🌐
Anintegratedworld
anintegratedworld.com › an-array-of-pointers-or-a-pointer-of-arrays
An array of pointers or a pointer of arrays? – An Integrated World
April 7, 2016 - To allocate values to a pointer to an array, the assignment operator (=) cannot be used. ... This won’t work and will result in “error: array type ‘char [32]’ is not assignable”. This is because arrays are not assignable. The strcpy or memcpy function has to be used from string.h library.
🌐
TechOnTheNet
techonthenet.com › c_language › standard_library_functions › string_h › memcpy.php
C Language: memcpy function (Copy Memory Block)
/* Example using memcpy by TechOnTheNet.com */ #include <stdio.h> #include <string.h> int main(int argc, const char * argv[]) { /* Create a place to store our results */ int result; /* Create two arrays to hold our data */ char original[50]; char newcopy[50]; /* Copy a string into the original array */ strcpy(original, "C memcpy at TechOnTheNet.com"); /* Copy the first 24 characters of the original array into the newcopy array */ result = memcpy(newcopy, original, 24); /* Set the character at position 24 to a null (char 0) in the newcopy array to ensure the string is terminated (This is important since memcpy does not initialize memory and printf expects a null at the end of a string) */ newcopy[24] = 0; /* Display the contents of the new copy */ printf("%s\n", newcopy); return 0; }
🌐
Sternum IoT
sternumiot.com › home › memcpy c function – syntax, examples, and security best practices
memcpy C Function | Syntax, Examples & Security Best Practices | Sternum IoT
January 30, 2024 - The function is commonly used in C programming for tasks such as copying the contents of one array to another, or for copying structures or other data types that are not handled by simple assignment.
🌐
GNU
gnu.org › software › libc › manual › html_node › Copying-Strings-and-Arrays.html
The GNU C Library - GNU Project - Free Software Foundation (FSF)
This glibc manual version 2.43 (latest) is available in the following formats: · The manual is available for the following releases of glibc: