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
  • 711
  • 8
  • 18
  • 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
  • 93,841
  • 5
  • 60
  • 108
  • 1
    I JUST realized. Where is the automatic pair programmer tool that hints to these idiotic mistakes? – fhchl Sep 22 '21 at 20:55
  • @fhchl LOL :-D Yeah, I've needed one of those myself. – Ted Lyngmo Sep 22 '21 at 20:56
  • it would be simpler and less error prone to use `memcpy(b, &a, sizeof a);` – tstanisl Sep 22 '21 at 21:13
  • @tstanisl `&a` makes a `double(*)[LEN]` instead of a `double*`. I find the latter clearer/simpler. I can agree to some extent about `sizeof a` but I went with `*b` for consistency with the `malloc`. – Ted Lyngmo Sep 22 '21 at 21:16
  • 2
    @fhchl `gcc -Wall -Werror` can help with some of those. – n. m. could be an AI Sep 22 '21 at 21:20
  • my variant will work with whatever `a` is going to be, not only `type[LEN]` – tstanisl Sep 22 '21 at 21:25
  • @tstanisl Yes, these `void*` functions are "forgiving" and don't care. I still like to match the types as best I can _as-if_ the function was actually `memcpy(double*, const double*, size_t);` – Ted Lyngmo Sep 22 '21 at 21:31
  • @n. 1.8e9-where's-my-share m these flags don't seem to catch the above problem. Hints to that main should return `int` though... – fhchl Sep 24 '21 at 08:59
  • They catch many other problems though. They [should be your default](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings). – n. m. could be an AI Sep 24 '21 at 09:09