Home > Enterprise >  How to copy from static array to dynamically allocated memory
How to copy from static array to dynamically allocated memory

Time:09-24

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 

CodePudding user response:

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

  • Related