memcpy()和memmove()没有按预期工作

时间:2016-12-02 03:12:17

标签: c arrays struct

我在使用struct中的struct数组时遇到了这个问题。我正在尝试使用memcpy在dict中设置条目数组。我得到了预期值和一些看似随机整数的混合作为输出。

奇怪的是,我在一些在线编译器中尝试了这个代码,并且工作正常。我认为它可能与重叠的内存区域有关,所以我尝试了memmove(),但结果是一样的。

我想我可能不会对词典使用malloc,但我不确定。似乎我不能将malloc用于内部数组或单个元素。我很感激任何帮助。

#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;
}

1 个答案:

答案 0 :(得分:6)

grayscaling

d = malloc(sizeof(d)); d; dict*sizeof d。看起来你的意思是sizeof(dict*)

相关问题