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 
2
  • Does this answer your question? Copy array to dynamically allocated memory Commented Sep 22, 2021 at 22:40
  • It does show that memcpy is the right tool, but here obviously getting the size right was the problem. Commented Sep 24, 2021 at 8:55

1 Answer 1

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().

Sign up to request clarification or add additional context in comments.

9 Comments

I JUST realized. Where is the automatic pair programmer tool that hints to these idiotic mistakes?
@fhchl LOL :-D Yeah, I've needed one of those myself.
it would be simpler and less error prone to use memcpy(b, &a, sizeof a);
@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.
@fhchl gcc -Wall -Werror can help with some of those.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.