简体   繁体   中英

memcpy() and memmove() not working as expected

I ran into this problem while working with a struct array within a struct. I'm trying to set the entry array in the dict using memcpy. I'm getting a mixture of the expected values and some seemingly random integers as output.

Oddly enough, I tried this code with some online compilers, and it worked fine. I thought that it might have to do with overlapping memory regions, so I tried memmove() but the result was the same.

I think I might be using malloc improperly for the dict, but I'm not sure. It seems I can't use malloc for the internal array, or for the individual elements. I'd appreciate any help.

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

typedef struct{
    int i;
} entry;

typedef struct{
    entry e[10];
    int i;
} dict;

dict* d;

void test(dict* di){
    printf("%d\n", di->i);
    int k;
    for (k = 0; k < 10; k ++){
        printf(("%d\n"),di->e[k].i);
    }
}

int main(){
    entry en[10];

    d = malloc(sizeof(d));

    int k;
    for (k = 0; k < 10; k++){
        en[k].i = k;
    }

    d->i = 50; 
    memcpy(d->e, en, 10*sizeof(entry));

    test(d);

    return 0;
}
d = malloc(sizeof(d));

d is a dict* ; sizeof d is sizeof(dict*) . Looks like you meant sizeof *d .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM