1

Why does b not hold 1., 2.?

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#define LEN 2

void main() {
    double a[LEN] = {1, 2};
    double* b = malloc(LEN * sizeof(*b));

    memcpy(b, a, LEN);
    for (size_t i = 0; i < LEN; i++)
    {
        printf("%.2f ", b[i]);
    }
    printf("\n");
}

Instead, I get

> gcc code.c                                                                                                                                                         
> ./a.out                                                                                                                                                                                   
0.00 0.00 
fhchl
  • 639
  • 7
  • 17
  • Does this answer your question? [Copy array to dynamically allocated memory](https://stackoverflow.com/questions/10577787/copy-array-to-dynamically-allocated-memory) – tstanisl Sep 22 '21 at 22:40
  • It does show that memcpy is the right tool, but here obviously getting the size right was the problem. – fhchl Sep 24 '21 at 08:55

1 Answers1

4

You forgot the sizeof in the memcpy

memcpy(b, a, LEN * sizeof *b);

As noted by @tstanisl in the comments, LEN * sizeof *b is the same as sizeof a, so you could make it:

double* b = malloc(sizeof a);
memcpy(b, a, sizeof a);

Also note that void main() isn't a valid signature for main. It should be int main().

Ted Lyngmo
  • 60,763
  • 5
  • 37
  • 77